#!/usr/bin/ruby
# jumpsaround - jumper game
# (c) 2021-2021 Alexander Kulbartsch

Size_x = 6
Size_y = 5

Jump = [[-1,-2], [1,-2], [-2,-1], [2,-1], [-2,1], [2,1], [-1,2], [1,2]]

$solutions  = 0
$roundtrips = 0

puts 'Hello, Jumper!'

# init
$board = Array.new(Size_x) { Array.new(Size_y) { 0 } }

def jumpto(x, y, iter)

	# ok - store position
	$board[x][y] = iter;

	# finished?
	if iter >= Size_x*Size_y
		# check for jumper roundtrips
		round = false
		Jump.each{ |jumpx|
			nx = x + jumpx[0]
			ny = y + jumpx[1]
           	# check if position is on the board
			next if nx<0 || nx>(Size_x-1) || ny<0 || ny>(Size_y-1)
            # detect roundtrip
			if $board[nx][ny] == 1
			  round = true
			  $roundtrips += 1
			end
			break if round
		}
        $solutions += 1
		printboard(round)
		$board[x][y] = 0
	end

	# try next jump
    Jump.each{ |jumpx|
		# new position
		nx = x + jumpx[0]
		ny = y + jumpx[1]
        # check if new position is on the board
		next if nx<0 || nx>(Size_x-1) || ny<0 || ny>(Size_y-1)
        #  check if new field position is still empty
		next if $board[nx][ny] != 0
		jumpto(nx, ny, iter + 1);
	}

	# this iteration is done
	$board[x][y] = 0

end

def printboard(round)
	puts "===== Solution # #{$solutions} - Roundtripps: #{$roundtrips} ====== "
	puts ' *** Roundtrip *** ' if round
    (0..(Size_y-1)).each do |i|
	    (0..(Size_x-1)).each do |j|
			print "%02d:" % $board[j][i]
		end
		puts
	end
# the following solution seems to be more idomatic, but it switches the x and y axis
# 	$board.each{ |boardx|
#         boardx.each{ |boardxy|
#     		print "%02d:" % boardxy
#     	}
#     	puts
#     }

	puts ''
end

jumpto(0, 0, 1)

puts 'I am done.'

# EOF