-- 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

print('Hello, Jumper!')

-- initialize the board
board = {}
for x = 1, Size_x do
	board[x] = {}
	for y = 1, Size_y do
		board[x][y] = 0
	end
end


function print_board(round)
	print()
	print("==== Solution #" .. solutions .. " - Roundtrips #" .. roundtrips .. " ====")
	if round then print('*** Roundtrip ***') end
	for y = Size_y, 1, -1 do
		for x = 1, Size_x do
			local val = board[x][y]
			if val < 10 then io.write(' ') end
			io.write(val .. ' ')
		end
		io.write('\n')
	end
end


function jump_to(x, y, iter)
	-- store position
	board[x][y] = iter

	-- check for roundtrip
	if iter == Size_x * Size_y then
		solutions = solutions + 1
		-- print_board(false)
		for i = 1, 8 do
			local nx = x + Jump[i][1]
			local ny = y + Jump[i][2]
			if nx >= 1 and nx <= Size_x and ny >= 1 and ny <= Size_y and board[nx][ny] == 1 then
				roundtrips = roundtrips + 1
				print_board(true)
				board[x][y] = 0
				return
			end
		end
	end

	-- try next jumps
	for i = 1, 8 do
		local nx = x + Jump[i][1]
		local ny = y + Jump[i][2]
		if nx >= 1 and nx <= Size_x and ny >= 1 and ny <= Size_y and board[nx][ny] == 0 then
			jump_to(nx, ny, iter + 1)
		end
	end

	board[x][y] = 0
end


jump_to(1, 1, 1)
print()
print("==== Solution #" .. solutions .. " - Roundtrips #" .. roundtrips .. " ====")
print('I am done.')

-- EOF