Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created June 30, 2016 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcoglan/f4f487745f4109514900dc550aefa470 to your computer and use it in GitHub Desktop.
Save jcoglan/f4f487745f4109514900dc550aefa470 to your computer and use it in GitHub Desktop.
type Peg = [Int]
data Game = Game { a :: Peg, b :: Peg, c :: Peg } deriving (Show)
type Sel = Game -> Peg
initPegs :: Int -> Game
initPegs n = Game { a = [n, (n-1) .. 1], b = [], c = [] }
hanoi :: Int -> Game -> Game
hanoi 1 Game { a = a, b = b, c = c } =
Game { a = take k a, b = b ++ drop k a, c = c }
where k = length a - 1
hanoi n game =
foldl transform game moves
where
transform game (k, selectors) =
arrange selectors $ hanoi k $ arrange selectors game
arrange (x, y, z) game =
Game { a = x game, b = y game, c = z game }
moves = [
(n-1, (a, c, b)),
(1, (a, b, c)),
(n-1, (c, b, a))
]
main = do
let n = 6
let pegs = initPegs n
print $ hanoi n pegs
def init_pegs(n)
{a: n.downto(1).to_a, b: [], c: []}
end
def hanoi(pegs, n, keys = pegs.keys)
a, b, c = keys
if n == 1
{
a => pegs[a] - [pegs[a].last],
b => pegs[b] + [pegs[a].last],
c => pegs[c]
}
else
moves = [
[n - 1, [a, c, b]],
[1, [a, b, c]],
[n - 1, [c, b, a]]
]
moves.inject(pegs) do |pegs, (k, keys)|
hanoi(pegs, k, keys)
end
end
end
n = ARGV.first.to_i
pegs = init_pegs(n)
p hanoi(pegs, n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment