Debian Codegraph @

ktour.sh

raw symbols SCIP
1 #!/bin/bash
2 # ktour.sh
3
4 # author: mendel cooper
5 # reldate: 12 Jan 2009
6 # license: public domain
7 # (Not much sense GPLing something that's pretty much in the common
8 #+ domain anyhow.)
9
10 ###################################################################
11 # The Knight's Tour, a classic problem. #
12 # ===================================== #
13 # The knight must move onto every square of the chess board, #
14 # but cannot revisit any square he has already visited. #
15 # #
16 # And just why is Sir Knight unwelcome for a return visit? #
17 # Could it be that he has a habit of partying into the wee hours #
18 #+ of the morning? #
19 # Possibly he leaves pizza crusts in the bed, empty beer bottles #
20 #+ all over the floor, and clogs the plumbing. . . . #
21 # #
22 # ------------------------------------------------------------- #
23 # #
24 # Usage: ktour.sh [start-square] [stupid] #
25 # #
26 # Note that start-square can be a square number #
27 #+ in the range 0 - 63 ... or #
28 # a square designator in conventional chess notation, #
29 # such as a1, f5, h3, etc. #
30 # #
31 # If start-square-number not supplied, #
32 #+ then starts on a random square somewhere on the board. #
33 # #
34 # "stupid" as second parameter sets the stupid strategy. #
35 # #
36 # Examples: #
37 # ktour.sh 23 starts on square #23 (h3) #
38 # ktour.sh g6 stupid starts on square #46, #
39 # using "stupid" (non-Warnsdorff) strategy. #
40 ###################################################################
41
42 DEBUG= # Set this to echo debugging info to stdout.
43 SUCCESS=0
44 FAIL=99
45 BADMOVE=-999
46 FAILURE=1
47 LINELEN=21 # How many moves to display per line.
48 # ---------------------------------------- #
49 # Board array params
50 ROWS=8 # 8 x 8 board.
51 COLS=8
52 let "SQUARES = $ROWS * $COLS"
53 let "MAX = $SQUARES - 1"
54 MIN=0
55 # 64 squares on board, indexed from 0 to 63.
56
57 VISITED=1
58 UNVISITED=-1
59 UNVSYM="##"
60 # ---------------------------------------- #
61 # Global variables.
62 startpos= # Starting position (square #, 0 - 63).
63 currpos= # Current position.
64 movenum= # Move number.
65 CRITPOS=37 # Have to patch for f5 starting position!
66
67 declare -i board
68 # Use a one-dimensional array to simulate a two-dimensional one.
69 # This can make life difficult and result in ugly kludges; see below.
70 declare -i moves # Offsets from current knight position.
71
72
73 initialize_board ()
74 {
75 local idx
76
77 for idx in {0..63}
78 do
79 board[$idx]=$UNVISITED
80 done
81 }
82
83
84
85 print_board ()
86 {
87 local idx
88
89 echo " _____________________________________"
90 for row in {7..0} # Reverse order of rows ...
91 do #+ so it prints in chessboard order.
92 let "rownum = $row + 1" # Start numbering rows at 1.
93 echo -n "$rownum |" # Mark board edge with border and
94 for column in {0..7} #+ "algebraic notation."
95 do
96 let "idx = $ROWS*$row + $column"
97 if [ ${board[idx]} -eq $UNVISITED ]
98 then
99 echo -n "$UNVSYM " ##
100 else # Mark square with move number.
101 printf "%02d " "${board[idx]}"; echo -n " "
102 fi
103 done
104 echo -e -n "\b\b\b|" # \b is a backspace.
105 echo # -e enables echoing escaped chars.
106 done
107
108 echo " -------------------------------------"
109 echo " a b c d e f g h"
110 }
111
112
113
114 failure()
115 { # Whine, then bail out.
116 echo
117 print_board
118 echo
119 echo " Waah!!! Ran out of squares to move to!"
120 echo -n " Knight's Tour attempt ended"
121 echo " on $(to_algebraic $currpos) [square #$currpos]"
122 echo " after just $movenum moves!"
123 echo
124 exit $FAIL
125 }
126
127
128
129 xlat_coords () # Translate x/y coordinates to board position
130 { #+ (board-array element #).
131 # For user input of starting board position as x/y coords.
132 # This function not used in initial release of ktour.sh.
133 # May be used in an updated version, for compatibility with
134 #+ standard implementation of the Knight's Tour in C, Python, etc.
135 if [ -z "$1" -o -z "$2" ]
136 then
137 return $FAIL
138 fi
139
140 local xc=$1
141 local yc=$2
142
143 let "board_index = $xc * $ROWS + yc"
144
145 if [ $board_index -lt $MIN -o $board_index -gt $MAX ]
146 then
147 return $FAIL # Strayed off the board!
148 else
149 return $board_index
150 fi
151 }
152
153
154
155 to_algebraic () # Translate board position (board-array element #)
156 { #+ to standard algebraic notation used by chess players.
157 if [ -z "$1" ]
158 then
159 return $FAIL
160 fi
161
162 local element_no=$1 # Numerical board position.
163 local col_arr=( a b c d e f g h )
164 local row_arr=( 1 2 3 4 5 6 7 8 )
165
166 let "row_no = $element_no / $ROWS"
167 let "col_no = $element_no % $ROWS"
168 t1=${col_arr[col_no]}; t2=${row_arr[row_no]}
169 local apos=$t1$t2 # Concatenate.
170 echo $apos
171 }
172
173
174
175 from_algebraic () # Translate standard algebraic chess notation
176 { #+ to numerical board position (board-array element #).
177 # Or recognize numerical input & return it unchanged.
178 if [ -z "$1" ]
179 then
180 return $FAIL
181 fi # If no command-line arg, then will default to random start pos.
182
183 local ix
184 local ix_count=0
185 local b_index # Board index [0-63]
186 local alpos="$1"
187
188 arow=${alpos:0:1} # position = 0, length = 1
189 acol=${alpos:1:1}
190
191 if [[ $arow =~ [[:digit:]] ]] # Numerical input?
192 then # POSIX char class
193 if [[ $acol =~ [[:alpha:]] ]] # Number followed by a letter? Illegal!
194 then return $FAIL
195 else if [ $alpos -gt $MAX ] # Off board?
196 then return $FAIL
197 else return $alpos # Return digit(s) unchanged . . .
198 fi #+ if within range.
199 fi
200 fi
201
202 if [[ $acol -eq $MIN || $acol -gt $ROWS ]]
203 then # Outside of range 1 - 8?
204 return $FAIL
205 fi
206
207 for ix in a b c d e f g h
208 do # Convert column letter to column number.
209 if [ "$arow" = "$ix" ]
210 then
211 break
212 fi
213 ((ix_count++)) # Find index count.
214 done
215
216 ((acol--)) # Decrementing converts to zero-based array.
217 let "b_index = $ix_count + $acol * $ROWS"
218
219 if [ $b_index -gt $MAX ] # Off board?
220 then
221 return $FAIL
222 fi
223
224 return $b_index
225
226 }
227
228
229 generate_moves () # Calculate all valid knight moves,
230 { #+ relative to current position ($1),
231 #+ and store in ${moves} array.
232 local kt_hop=1 # One square :: short leg of knight move.
233 local kt_skip=2 # Two squares :: long leg of knight move.
234 local valmov=0 # Valid moves.
235 local row_pos; let "row_pos = $1 % $COLS"
236
237
238 let "move1 = -$kt_skip + $ROWS" # 2 sideways to-the-left, 1 up
239 if [[ `expr $row_pos - $kt_skip` -lt $MIN ]] # An ugly, ugly kludge!
240 then # Can't move off board.
241 move1=$BADMOVE # Not even temporarily.
242 else
243 ((valmov++))
244 fi
245 let "move2 = -$kt_hop + $kt_skip * $ROWS" # 1 sideways to-the-left, 2 up
246 if [[ `expr $row_pos - $kt_hop` -lt $MIN ]] # Kludge continued ...
247 then
248 move2=$BADMOVE
249 else
250 ((valmov++))
251 fi
252 let "move3 = $kt_hop + $kt_skip * $ROWS" # 1 sideways to-the-right, 2 up
253 if [[ `expr $row_pos + $kt_hop` -ge $COLS ]]
254 then
255 move3=$BADMOVE
256 else
257 ((valmov++))
258 fi
259 let "move4 = $kt_skip + $ROWS" # 2 sideways to-the-right, 1 up
260 if [[ `expr $row_pos + $kt_skip` -ge $COLS ]]
261 then
262 move4=$BADMOVE
263 else
264 ((valmov++))
265 fi
266 let "move5 = $kt_skip - $ROWS" # 2 sideways to-the-right, 1 dn
267 if [[ `expr $row_pos + $kt_skip` -ge $COLS ]]
268 then
269 move5=$BADMOVE
270 else
271 ((valmov++))
272 fi
273 let "move6 = $kt_hop - $kt_skip * $ROWS" # 1 sideways to-the-right, 2 dn
274 if [[ `expr $row_pos + $kt_hop` -ge $COLS ]]
275 then
276 move6=$BADMOVE
277 else
278 ((valmov++))
279 fi
280 let "move7 = -$kt_hop - $kt_skip * $ROWS" # 1 sideways to-the-left, 2 dn
281 if [[ `expr $row_pos - $kt_hop` -lt $MIN ]]
282 then
283 move7=$BADMOVE
284 else
285 ((valmov++))
286 fi
287 let "move8 = -$kt_skip - $ROWS" # 2 sideways to-the-left, 1 dn
288 if [[ `expr $row_pos - $kt_skip` -lt $MIN ]]
289 then
290 move8=$BADMOVE
291 else
292 ((valmov++))
293 fi # There must be a better way to do this.
294
295 local m=( $valmov $move1 $move2 $move3 $move4 $move5 $move6 $move7 $move8 )
296 # ${moves[0]} = number of valid moves.
297 # ${moves[1]} ... ${moves[8]} = possible moves.
298 echo "${m[*]}" # Elements of array to stdout for capture in a var.
299
300 }
301
302
303
304 is_on_board () # Is position actually on the board?
305 {
306 if [[ "$1" -lt "$MIN" || "$1" -gt "$MAX" ]]
307 then
308 return $FAILURE
309 else
310 return $SUCCESS
311 fi
312 }
313
314
315
316 do_move () # Move the knight!
317 {
318 local valid_moves=0
319 local aapos
320 currposl="$1"
321 lmin=$ROWS
322 iex=0
323 squarel=
324 mpm=
325 mov=
326 declare -a p_moves
327
328 ########################## DECIDE-MOVE #############################
329 if [ $startpos -ne $CRITPOS ]
330 then # CRITPOS = square #37
331 decide_move
332 else # Needs a special patch for startpos=37 !!!
333 decide_move_patched # Why this particular move and no other ???
334 fi
335 ####################################################################
336
337 (( ++movenum )) # Increment move count.
338 let "square = $currposl + ${moves[iex]}"
339
340 ################## DEBUG ###############
341 if [ "$DEBUG" ]
342 then debug # Echo debugging information.
343 fi
344 ##############################################
345
346 if [[ "$square" -gt $MAX || "$square" -lt $MIN ||
347 ${board[square]} -ne $UNVISITED ]]
348 then
349 (( --movenum )) # Decrement move count,
350 echo "RAN OUT OF SQUARES!!!" #+ since previous one was invalid.
351 return $FAIL
352 fi
353
354 board[square]=$movenum
355 currpos=$square # Update current position.
356 ((valid_moves++)); # moves[0]=$valid_moves
357 aapos=$(to_algebraic $square)
358 echo -n "$aapos "
359 test $(( $Moves % $LINELEN )) -eq 0 && echo
360 # Print LINELEN=21 moves per line. A valid tour shows 3 complete lines.
361 return $valid_moves # Found a square to move to!
362 }
363
364
365
366 do_move_stupid() # Dingbat algorithm,
367 { #+ courtesy of script author, *not* Warnsdorff.
368 local valid_moves=0
369 local movloc
370 local squareloc
371 local aapos
372 local cposloc="$1"
373
374 for movloc in {1..8}
375 do # Move to first-found unvisited square.
376 let "squareloc = $cposloc + ${moves[movloc]}"
377 is_on_board $squareloc
378 if [ $? -eq $SUCCESS ] && [ ${board[squareloc]} -eq $UNVISITED ]
379 then # Add conditions to above if-test to improve algorithm.
380 (( ++movenum ))
381 board[squareloc]=$movenum
382 currpos=$squareloc # Update current position.
383 ((valid_moves++)); # moves[0]=$valid_moves
384 aapos=$(to_algebraic $squareloc)
385 echo -n "$aapos "
386 test $(( $Moves % $LINELEN )) -eq 0 && echo # Print 21 moves/line.
387 return $valid_moves # Found a square to move to!
388 fi
389 done
390
391 return $FAIL
392 # If no square found in all 8 loop iterations,
393 #+ then Knight's Tour attempt ends in failure.
394
395 # Dingbat algorithm will typically fail after about 30 - 40 moves,
396 #+ but executes _much_ faster than Warnsdorff's in do_move() function.
397 }
398
399
400
401 decide_move () # Which move will we make?
402 { # But, fails on startpos=37 !!!
403 for mov in {1..8}
404 do
405 let "squarel = $currposl + ${moves[mov]}"
406 is_on_board $squarel
407 if [[ $? -eq $SUCCESS && ${board[squarel]} -eq $UNVISITED ]]
408 then # Find accessible square with least possible future moves.
409 # This is Warnsdorff's algorithm.
410 # What happens is that the knight wanders toward the outer edge
411 #+ of the board, then pretty much spirals inward.
412 # Given two or more possible moves with same value of
413 #+ least-possible-future-moves, this implementation chooses
414 #+ the _first_ of those moves.
415 # This means that there is not necessarily a unique solution
416 #+ for any given starting position.
417
418 possible_moves $squarel
419 mpm=$?
420 p_moves[mov]=$mpm
421
422 if [ $mpm -lt $lmin ] # If less than previous minimum ...
423 then # ^^
424 lmin=$mpm # Update minimum.
425 iex=$mov # Save index.
426 fi
427
428 fi
429 done
430 }
431
432
433
434 decide_move_patched () # Decide which move to make,
435 { # ^^^^^^^ #+ but only if startpos=37 !!!
436 for mov in {1..8}
437 do
438 let "squarel = $currposl + ${moves[mov]}"
439 is_on_board $squarel
440 if [[ $? -eq $SUCCESS && ${board[squarel]} -eq $UNVISITED ]]
441 then
442 possible_moves $squarel
443 mpm=$?
444 p_moves[mov]=$mpm
445
446 if [ $mpm -le $lmin ] # If less-than-or equal to prev. minimum!
447 then # ^^
448 lmin=$mpm
449 iex=$mov
450 fi
451
452 fi
453 done # There has to be a better way to do this.
454 }
455
456
457
458 possible_moves () # Calculate number of possible moves,
459 { #+ given the current position.
460
461 if [ -z "$1" ]
462 then
463 return $FAIL
464 fi
465
466 local curr_pos=$1
467 local valid_movl=0
468 local icx=0
469 local movl
470 local sq
471 declare -a movesloc
472
473 movesloc=( $(generate_moves $curr_pos) )
474
475 for movl in {1..8}
476 do
477 let "sq = $curr_pos + ${movesloc[movl]}"
478 is_on_board $sq
479 if [ $? -eq $SUCCESS ] && [ ${board[sq]} -eq $UNVISITED ]
480 then
481 ((valid_movl++));
482 fi
483 done
484
485 return $valid_movl # Found a square to move to!
486 }
487
488
489 strategy ()
490 {
491 echo
492
493 if [ -n "$STUPID" ]
494 then
495 for Moves in {1..63}
496 do
497 cposl=$1
498 moves=( $(generate_moves $currpos) )
499 do_move_stupid "$currpos"
500 if [ $? -eq $FAIL ]
501 then
502 failure
503 fi
504 done
505 fi
506
507 # Don't need an "else" clause here,
508 #+ because Stupid Strategy will always fail and exit!
509 for Moves in {1..63}
510 do
511 cposl=$1
512 moves=( $(generate_moves $currpos) )
513 do_move "$currpos"
514 if [ $? -eq $FAIL ]
515 then
516 failure
517 fi
518
519 done
520 # Could have condensed above two do-loops into a single one,
521 echo #+ but this would have slowed execution.
522
523 print_board
524 echo
525 echo "Knight's Tour ends on $(to_algebraic $currpos) [square #$currpos]."
526 return $SUCCESS
527 }
528
529 debug ()
530 { # Enable this by setting DEBUG=1 near beginning of script.
531 local n
532
533 echo "================================="
534 echo " At move number $movenum:"
535 echo " *** possible moves = $mpm ***"
536 # echo "### square = $square ###"
537 echo "lmin = $lmin"
538 echo "${moves[@]}"
539
540 for n in {1..8}
541 do
542 echo -n "($n):${p_moves[n]} "
543 done
544
545 echo
546 echo "iex = $iex :: moves[iex] = ${moves[iex]}"
547 echo "square = $square"
548 echo "================================="
549 echo
550 } # Gives pretty complete status after ea. move.
551
552
553
554 # =============================================================== #
555 # int main () {
556 from_algebraic "$1"
557 startpos=$?
558 if [ "$startpos" -eq "$FAIL" ] # Okay even if no $1.
559 then # ^^^^^^^^^^^ Okay even if input -lt 0.
560 echo "No starting square specified (or illegal input)."
561 let "startpos = $RANDOM % $SQUARES" # 0 - 63 permissable range.
562 fi
563
564
565 if [ "$2" = "stupid" ]
566 then
567 STUPID=1
568 echo -n " ### Stupid Strategy ###"
569 else
570 STUPID=''
571 echo -n " *** Warnsdorff's Algorithm ***"
572 fi
573
574
575 initialize_board
576
577 movenum=0
578 board[startpos]=$movenum # Mark each board square with move number.
579 currpos=$startpos
580 algpos=$(to_algebraic $startpos)
581
582 echo; echo "Starting from $algpos [square #$startpos] ..."; echo
583 echo -n "Moves:"
584
585 strategy "$currpos"
586
587 echo
588
589 exit 0 # return 0;
590
591 # } # End of main() pseudo-function.
592 # =============================================================== #
593
594
595 # Exercises:
596 # ---------
597 #
598 # 1) Extend this example to a 10 x 10 board or larger.
599 # 2) Improve the "stupid strategy" by modifying the
600 # do_move_stupid function.
601 # Hint: Prevent straying into corner squares in early moves
602 # (the exact opposite of Warnsdorff's algorithm!).
603 # 3) This script could stand considerable improvement and
604 # streamlining, especially in the poorly-written
605 # generate_moves() function
606 # and in the DECIDE-MOVE patch in the do_move() function.
607 # Must figure out why standard algorithm fails for startpos=37 ...
608 #+ but _not_ on any other, including symmetrical startpos=26.
609 # Possibly, when calculating possible moves, counts the move back
610 #+ to the originating square. If so, it might be a relatively easy fix.