// jumpsaround.v - jumper game
// (c) 2020 Alexander Kulbartsch
// 
// V language based https://vlang.io/
// basic version

const ( 
	// {{-1,-2}, {1,-2}, {-2,-1}, {2,-1}, {-2,1}, {2,1}, {-1,2}, {1,2}}
	jumpx = [-1,  1, -2,  2, -2,  2, -1,  1]
	jumpy = [-2, -2, -1, -1,  1,  1,  2,  2]
)

// Main
fn main() {
	println('Hello, Jumper!')	

	sizex := 6
	sizey := 5

	mut board := [0].repeat(sizex * sizey)

    solutions, roundtrips := jumpto(mut board, sizex, sizey, 0, 0, 1, 0, 0)

	println('===== Solutions:$solutions - Roundtripps:$roundtrips ====== ')    
	println('I am done.')
}


// Jump to a new postion 
fn jumpto(mut board []int, sizex int, sizey int, x int, y int, iter_in int, solutions_in int, roundtrips_in int) (int, int) {

	mut solutions  := solutions_in
	mut roundtrips := roundtrips_in 
	mut iter       := iter_in

	// store position
    // board_set(mut board, sizex, sizey, x, y, iter)
    board[x + y * sizex] = iter

    // check if finished
    mut round := false
    if  iter == sizex * sizey {
	    for i, jx in jumpx {
	        nx := x + jx
	        ny := y + jumpy[i]

	        // new position still on board
	        if nx<0 || nx>(sizex-1) || ny<0 || ny>(sizey-1) { continue }

	    	// check for roundtrips
	    	if board[nx + ny * sizex] == 1 { 
	    		round = true
	    		roundtrips++
	    		print_board(board, sizex, sizey, round, iter, solutions, roundtrips)
	    		break 
	    	} 
	    }

	    board[x + y * sizex] = 0
	    return solutions + 1, roundtrips
	}

	// try next jump
	iter++
    for i, jx in jumpx {
        nx := x + jx
        ny := y + jumpy[i]

        // new position still on board
        if nx<0 || nx>(sizex-1) || ny<0 || ny>(sizey-1) { continue }

    	// check if new position is empty and jump to it
    	if board[nx + ny * sizex] == 0 { 
    		solutions, roundtrips = jumpto(mut board, sizex, sizey, nx, ny, iter, solutions, roundtrips)
    	} 
    }

   	board[x + y * sizex] = 0
  	return solutions, roundtrips
}


// print the board
fn print_board(board []int, sizex int, sizey int, round bool, iter int, solutions int, roundtrips int) {
	println('===== Solutions:$solutions - Roundtripps:$roundtrips ====== ')    
	if round {
		println('** Roundtrip **')
	}
	for i, f in board {
		if f < 10 { print(' ') }
		print('$f:')
		if (i+1) % sizex == 0 {
			println('')
		}
	}
	println('')
}

// EOF
