1 // jumpsaround.go - jumper game
    2 // (c) 2020 Alexander Kulbartsch
    3 // 
    4 // use type inference and int types when neccessary
    5 // (slightly performace optimized version: valid jumpes checked bevore iteration.)
    6 
    7 package main
    8 
    9 import (
   10     "fmt"
   11 )
   12 
   13 const SIZEX = 6
   14 const SIZEY = 5
   15 
   16 type boardt [SIZEX][SIZEY]int
   17 
   18 var board boardt
   19 var jump = [8][2]int{{-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}}
   20 var solutions = 0
   21 var roundtrips = 0
   22 
   23 func main() {
   24     fmt.Println("Hello, Jumper!")
   25 
   26     jumpto(0, 0, 1)
   27 
   28     fmt.Println("I am done.")
   29 }
   30 
   31 func jumpto(x, y, iter int) {
   32 
   33     // ok - store position
   34     board[x][y] = iter
   35 
   36     // finished?
   37     if iter >= SIZEX*SIZEY {
   38 
   39         // check for jumper roundtrips
   40         round := false
   41         for _, d := range jump {
   42             nx := x + d[0]
   43             ny := y + d[1]
   44             // check if position is on the board
   45             if nx < 0 || nx > (SIZEX-1) || ny < 0 || ny > (SIZEY-1) {
   46                 continue
   47             }
   48             // detect roundtrip
   49             if board[nx][ny] == 1 {
   50                 round = true
   51                 roundtrips++
   52                 break
   53             } // True
   54         }
   55 
   56         solutions++
   57         if round == true {
   58             printboard(round)
   59         }
   60         board[x][y] = 0
   61         return
   62     }
   63 
   64     // try next jump
   65     for _, d := range jump {
   66         nx := x + d[0]
   67         ny := y + d[1]
   68 
   69         // check if position is on the board
   70         if nx < 0 || nx > (SIZEX-1) || ny < 0 || ny > (SIZEY-1) {
   71             continue
   72         }
   73 
   74         //  check if new field position is still empty
   75         if board[nx][ny] != 0 {
   76             continue
   77         } // True
   78 
   79         jumpto(nx, ny, iter+1)
   80     }
   81 
   82     // this iteration is done
   83     board[x][y] = 0
   84 
   85 }
   86 
   87 func printboard(round bool) {
   88     fmt.Println("===== Solution #", solutions, " - Roundtripps:", roundtrips, " ====== ")
   89     if round == true {
   90         fmt.Println(" *** Roundtrip *** ")
   91     }
   92     fmt.Println("")
   93     for i := 0; i < SIZEY; i++ {
   94         for j := 0; j < SIZEX; j++ {
   95             fmt.Printf("%2d:", board[j][i])
   96         }
   97         fmt.Println("")
   98     }
   99     fmt.Println("")
  100 }
  101 
  102 // EOF