Topswops
editable example
Click the pencil to open this in an editor, change it, and run it in your browser. The same solution is posted on Rosetta Code.
ghul
use IO.Std.write_line
use Collections
swaps(deck: int[]) -> int => (
let cards = LIST()
for card in deck do
cards.add(card)
od
let count mut = 0
while cards[0] != 1 do
let top_card = cards[0]
let last = top_card - 1
for i in 0::(top_card - 1) / 2 do
let held = cards[i]
cards[i] = cards[last - i]
cards[last - i] = held
od
count = count + 1
od
count
)
topswops(n: int) -> int => (
let deck = LIST()
for card in 1::n do
deck.add(card)
od
let best mut = 0
let search = (position: int) -> void rec is
if position == n then
let rounds = swaps(deck.to_array())
if rounds > best then
best = rounds
fi
else
for i in position::(n - 1) do
let held = deck[position]
deck[position] = deck[i]
deck[i] = held
rec(position + 1)
let put_back = deck[position]
deck[position] = deck[i]
deck[i] = put_back
od
fi
si
search(0)
best
)
for n in 1::10 do
write_line("{n}: {topswops(n)}")
od