permutations iterator
This commit is contained in:
parent
c552834741
commit
86ef069848
23
main.nim
23
main.nim
@ -1,4 +1,4 @@
|
||||
import options, sequtils, sugar
|
||||
import algorithm, options, sequtils, sugar
|
||||
|
||||
|
||||
type
|
||||
@ -18,6 +18,7 @@ type
|
||||
Board = object
|
||||
squares: array[1..16, Square]
|
||||
camels: array[Color, range[1..16]]
|
||||
leader: Color
|
||||
|
||||
|
||||
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:
|
||||
if c == color:
|
||||
let subStack = b[startPos].camels[i .. ^1]
|
||||
b[endPos].camels.add(subStack)
|
||||
if prepend:
|
||||
# figure out how to prepend a sequence to another sequence
|
||||
b[endPos].camels.insert(subStack)
|
||||
else:
|
||||
b[endPos].camels.add(subStack)
|
||||
|
||||
b[startPos].camels[i .. ^1] = @[]
|
||||
for moved in subStack:
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
# b.display(1, 5)
|
||||
b.display(1, 5)
|
||||
b.preRoll
|
||||
let c = b.dup(advance((cRed, range[1..3]3)))
|
||||
b.display(1, 5)
|
||||
|
Loading…
x
Reference in New Issue
Block a user