1 #!/usr/bin/ruby 2 # jumpsaround - jumper game 3 # (c) 2021-2021 Alexander Kulbartsch 4 5 Size_x = 6 6 Size_y = 5 7 8 Jump = [[-1,-2], [1,-2], [-2,-1], [2,-1], [-2,1], [2,1], [-1,2], [1,2]] 9 10 $solutions = 0 11 $roundtrips = 0 12 13 puts 'Hello, Jumper!' 14 15 # init 16 $board = Array.new(Size_x) { Array.new(Size_y) { 0 } } 17 18 def jumpto(x, y, iter) 19 20 # ok - store position 21 $board[x][y] = iter; 22 23 # finished? 24 if iter >= Size_x*Size_y 25 # check for jumper roundtrips 26 round = false 27 Jump.each{ |jumpx| 28 nx = x + jumpx[0] 29 ny = y + jumpx[1] 30 # check if position is on the board 31 next if nx<0 || nx>(Size_x-1) || ny<0 || ny>(Size_y-1) 32 # detect roundtrip 33 if $board[nx][ny] == 1 34 round = true 35 $roundtrips += 1 36 end 37 break if round 38 } 39 $solutions += 1 40 printboard(round) 41 $board[x][y] = 0 42 end 43 44 # try next jump 45 Jump.each{ |jumpx| 46 # new position 47 nx = x + jumpx[0] 48 ny = y + jumpx[1] 49 # check if new position is on the board 50 next if nx<0 || nx>(Size_x-1) || ny<0 || ny>(Size_y-1) 51 # check if new field position is still empty 52 next if $board[nx][ny] != 0 53 jumpto(nx, ny, iter + 1); 54 } 55 56 # this iteration is done 57 $board[x][y] = 0 58 59 end 60 61 def printboard(round) 62 puts "===== Solution # #{$solutions} - Roundtripps: #{$roundtrips} ====== " 63 puts ' *** Roundtrip *** ' if round 64 (0..(Size_y-1)).each do |i| 65 (0..(Size_x-1)).each do |j| 66 print "%02d:" % $board[j][i] 67 end 68 puts 69 end 70 # the following solution seems to be more idomatic, but it switches the x and y axis 71 # $board.each{ |boardx| 72 # boardx.each{ |boardxy| 73 # print "%02d:" % boardxy 74 # } 75 # puts 76 # } 77 78 puts '' 79 end 80 81 jumpto(0, 0, 1) 82 83 puts 'I am done.' 84 85 # EOF