My assignment is to solve the Towers of Hanoi for any number using recursion. I wrote my code in C++.
Rules:
Basically on each call you need to do the following steps:
Move the n-1 stack of discs to the 4th peg (or 2nd when going backwards)
Move the nth disc to the middle (3rd peg)
Move the n-1 stack back to the 2nd peg (i.e. 4th when going backwards)
Move the nth disc to its destination
Move the n-1 stack to the destination
So you need 3 recursive calls without memoization.
function hanoi5(n) {
let out = []
move(n, 0, 4)
console.log(out.length + " steps")
console.log(out.join("\n"))
function move(n, from, to) {
if (n == 1) {
let dir = from < to ? 1 : -1
for (let i = from; i != to; i += dir)
out.push("move disc 1 from peg " + (i+1) + " to peg " + (i+1+dir))
} else if (from < to) {
move(n - 1, from, 3)
for (let i = from; i < 2; i++)
out.push("move disc " + n + " from peg " + (i+1) + " to peg " + (i+2))
move(n - 1, 3, 1)
for (let i = 2; i < to; i++)
out.push("move disc " + n + " from peg " + (i+1) + " to peg " + (i+2))
move(n - 1, 1, to)
} else {
move(n - 1, 3, 1)
out.push("move disc " + n + " from peg 3 to peg 2")
move(n - 1, 1, 3)
out.push("move disc " + n + " from peg 2 to peg 1")
move(n - 1, 3, 1)
}
}
}
hanoi5(3)