permutations iterator
This commit is contained in:
parent
c552834741
commit
86ef069848
25
main.nim
25
main.nim
@ -1,4 +1,4 @@
|
|||||||
import options, sequtils, sugar
|
import algorithm, options, sequtils, sugar
|
||||||
|
|
||||||
|
|
||||||
type
|
type
|
||||||
@ -18,6 +18,7 @@ type
|
|||||||
Board = object
|
Board = object
|
||||||
squares: array[1..16, Square]
|
squares: array[1..16, Square]
|
||||||
camels: array[Color, range[1..16]]
|
camels: array[Color, range[1..16]]
|
||||||
|
leader: Color
|
||||||
|
|
||||||
|
|
||||||
proc `[]`(b: var Board, idx: range[1..16]): var Square =
|
proc `[]`(b: var Board, idx: range[1..16]): var Square =
|
||||||
@ -58,18 +59,32 @@ proc advance(b: var Board, die: Die) =
|
|||||||
for i, c in b[startPos].camels:
|
for i, c in b[startPos].camels:
|
||||||
if c == color:
|
if c == color:
|
||||||
let subStack = b[startPos].camels[i .. ^1]
|
let subStack = b[startPos].camels[i .. ^1]
|
||||||
b[endPos].camels.add(subStack)
|
|
||||||
if prepend:
|
if prepend:
|
||||||
# figure out how to prepend a sequence to another sequence
|
b[endPos].camels.insert(subStack)
|
||||||
else:
|
else:
|
||||||
b[startPos].camels[i .. ^1] = @[]
|
b[endPos].camels.add(subStack)
|
||||||
|
|
||||||
|
b[startPos].camels[i .. ^1] = @[]
|
||||||
for moved in subStack:
|
for moved in subStack:
|
||||||
b.camels[moved] = endPos
|
b.camels[moved] = endPos
|
||||||
|
b.leader = b[b.camels.max][^1] # top camel in the last currently-occupied space
|
||||||
|
|
||||||
break # breaking the outer loop here, not the inner
|
break # breaking the outer loop here, not the inner
|
||||||
|
|
||||||
|
|
||||||
|
iterator allPermutations[T](x: seq[T]): seq[T] =
|
||||||
|
# returns all permutations of a given array. Order is wonky but we don't care.
|
||||||
|
var workingCopy = x
|
||||||
|
yield workingCopy
|
||||||
|
while workingCopy.nextPermutation: # this mutates workingCopy
|
||||||
|
yield workingCopy
|
||||||
|
workingCopy = x
|
||||||
|
while workingCopy.prevPermutation:
|
||||||
|
yield workingCopy
|
||||||
|
|
||||||
|
|
||||||
var b: Board
|
var b: Board
|
||||||
# b.display(1, 5)
|
b.display(1, 5)
|
||||||
b.preRoll
|
b.preRoll
|
||||||
let c = b.dup(advance((cRed, range[1..3]3)))
|
let c = b.dup(advance((cRed, range[1..3]3)))
|
||||||
b.display(1, 5)
|
b.display(1, 5)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user