Towers Hanoi

Recursion script/alias to solve the Towers of Hanoi puzzle.

Alias:
^hanoi (\d+) (\w+) (\w+)$

hanoi(tonumber(matches[2]),matches[3],matches[4])

Script:

function hanoi(discNum, startPeg, endPeg)
	pegs = {["left"] = 1,["middle"] = 2,["right"] = 3}
	discs = {[1] = "ten",[2] = "twenty",[3] = "thirty",[4] = "forty",[5] = "fifty",[6] = "sixty"}
	currDisc = 1
	send(hanoiRec(discNum, startPeg, endPeg))
	
end
function hanoiRec(discNum, startPeg, endPeg)
	if (discNum == 1) then
		return "get " .. discs[1] .." from " .. startPeg .. ";;put " .. discs[1] .. " on " .. endPeg .. ";;"
	else
		local helpPeg = 6 - pegs[startPeg] - pegs[endPeg]
		if helpPeg == 1 then helpPeg = "left" end
		if helpPeg == 2 then helpPeg = "middle" end
		if helpPeg == 3 then helpPeg = "right" end
		local solution1 = hanoiRec(discNum-1,startPeg,helpPeg)
		local innerStep = "get " .. discs[discNum] .." from " .. startPeg .. ";;put " .. discs[discNum] .. " on " .. endPeg .. ";;"		
		local solution2 = hanoiRec(discNum-1,helpPeg,endPeg)
		final = solution1 .. innerStep .. solution2
		return(final)
	end
end
You can c/p both directly into mudlet(though it assumes your command separator is ';;', and if it's something else, this won't work as is). To solve a puzzle, enter the number of discs to move, where they are, and where they're being moved to. So: hanoi 3 right left - attempts to move the three lightest discs from the right platform to the left platform. Any number from 1 to 6 should work.
Sign In or Register to comment.