Skip to content

Instantly share code, notes, and snippets.

@eigenhombre
Last active May 20, 2022 14:01
Show Gist options
  • Save eigenhombre/5207de98e886495dd7e5cb574da67aef to your computer and use it in GitHub Desktop.
Save eigenhombre/5207de98e886495dd7e5cb574da67aef to your computer and use it in GitHub Desktop.
War Permutations - Uniqueness and Tracking
// See http://johnj.com/art/warperms/ for context....
package main
import (
"fmt"
"math/rand"
"os"
"time"
)
const permsfile_base = ".warperm.permutations.txt"
func load_permutations(permsfile string) []int {
if _, err := os.Stat(permsfile); err != nil {
if os.IsNotExist(err) {
return []int{}
}
panic(err)
}
f, err := os.Open(permsfile)
if err != nil {
panic(err)
}
defer f.Close()
var perms []int
for {
var perm int
_, err := fmt.Fscanf(f, "%d\n", &perm)
if err != nil {
break
}
perms = append(perms, perm)
}
return perms
}
func save_permutations(permsfile string, perms []int) {
f, err := os.OpenFile(permsfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer f.Close()
for _, perm := range perms {
_, err = fmt.Fprintf(f, "%d\n", perm)
if err != nil {
panic(err)
}
}
}
// generate_permutation generates a random permutation of the numbers 0 to 8.
// It is not very efficient - use a map instead.
func generate_permutation() int {
// generate new permutation
positions := make([]int, 9)
for i := 0; i < 9; i++ {
positions[i] = i + 1
}
ret := 0
for {
// pick a random position
pos := rand.Intn(len(positions))
ret = ret*10 + positions[pos]
rest := positions[:pos]
rest = append(rest, positions[pos+1:]...)
positions = rest
if len(positions) == 0 {
break
}
}
return ret
}
func contains(perms []int, perm int) bool {
for _, p := range perms {
if p == perm {
return true
}
}
return false
}
func new_unique_permutation(perms []int) int {
perm := generate_permutation()
for {
if contains(perms, perm) {
perm = generate_permutation()
} else {
break
}
}
return perm
}
func main() {
permsfile := os.Getenv("HOME") + "/" + permsfile_base
rand.Seed(time.Now().UnixNano())
fmt.Println("Loading existing permutations...")
perms := load_permutations(permsfile)
newperms := []int{}
n := 1
fmt.Println("Generating", n, "new permutation(s)...")
for i := 0; i < n; i++ {
perm := new_unique_permutation(perms)
perms = append(perms, perm)
newperms = append(newperms, perm)
fmt.Println(" ", perm)
}
fmt.Println("Saving new permutations...")
save_permutations(permsfile, newperms)
fmt.Println("OK")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment