1 // jumpsaround.v - jumper game 2 // (c) 2020 Alexander Kulbartsch 3 // 4 // V language based https://vlang.io/ 5 // basic version 6 7 const ( 8 // {{-1,-2}, {1,-2}, {-2,-1}, {2,-1}, {-2,1}, {2,1}, {-1,2}, {1,2}} 9 jumpx = [-1, 1, -2, 2, -2, 2, -1, 1] 10 jumpy = [-2, -2, -1, -1, 1, 1, 2, 2] 11 ) 12 13 // Main 14 fn main() { 15 println('Hello, Jumper!') 16 17 sizex := 6 18 sizey := 5 19 20 mut board := [0].repeat(sizex * sizey) 21 22 solutions, roundtrips := jumpto(mut board, sizex, sizey, 0, 0, 1, 0, 0) 23 24 println('===== Solutions:$solutions - Roundtripps:$roundtrips ====== ') 25 println('I am done.') 26 } 27 28 29 // Jump to a new postion 30 fn jumpto(mut board []int, sizex int, sizey int, x int, y int, iter_in int, solutions_in int, roundtrips_in int) (int, int) { 31 32 mut solutions := solutions_in 33 mut roundtrips := roundtrips_in 34 mut iter := iter_in 35 36 // store position 37 // board_set(mut board, sizex, sizey, x, y, iter) 38 board[x + y * sizex] = iter 39 40 // check if finished 41 mut round := false 42 if iter == sizex * sizey { 43 for i, jx in jumpx { 44 nx := x + jx 45 ny := y + jumpy[i] 46 47 // new position still on board 48 if nx<0 || nx>(sizex-1) || ny<0 || ny>(sizey-1) { continue } 49 50 // check for roundtrips 51 if board[nx + ny * sizex] == 1 { 52 round = true 53 roundtrips++ 54 print_board(board, sizex, sizey, round, iter, solutions, roundtrips) 55 break 56 } 57 } 58 59 board[x + y * sizex] = 0 60 return solutions + 1, roundtrips 61 } 62 63 // try next jump 64 iter++ 65 for i, jx in jumpx { 66 nx := x + jx 67 ny := y + jumpy[i] 68 69 // new position still on board 70 if nx<0 || nx>(sizex-1) || ny<0 || ny>(sizey-1) { continue } 71 72 // check if new position is empty and jump to it 73 if board[nx + ny * sizex] == 0 { 74 solutions, roundtrips = jumpto(mut board, sizex, sizey, nx, ny, iter, solutions, roundtrips) 75 } 76 } 77 78 board[x + y * sizex] = 0 79 return solutions, roundtrips 80 } 81 82 83 // print the board 84 fn print_board(board []int, sizex int, sizey int, round bool, iter int, solutions int, roundtrips int) { 85 println('===== Solutions:$solutions - Roundtripps:$roundtrips ====== ') 86 if round { 87 println('** Roundtrip **') 88 } 89 for i, f in board { 90 if f < 10 { print(' ') } 91 print('$f:') 92 if (i+1) % sizex == 0 { 93 println('') 94 } 95 } 96 println('') 97 } 98 99 // EOF