Tuesday, September 05, 2006

Hanoi: A simple C# solution

Here is a simple towers of Hanoi solution in C# public static void SolveSubHanoi(int n, string start, string end, string intermediate) { System.Console.WriteLine(n + " " + start + " " + end + " " + intermediate); if (n <= 1) { //move topmost from start peg to end peg System.Console.WriteLine("c1:" + start + " --> " + end); } else { //move n-1 discs to intermediate position SolveSubHanoi(n - 1, start, intermediate, end); //now move the n(th) disc from start to end System.Console.WriteLine("c2:" + start + " --> " + end); //now move the n-1 discs from intermediate to end SolveSubHanoi(n - 1, intermediate, end, start); } } And all you do is call it so: SolveSubHanoi(n, "Peg A", "Peg B", "Peg C"); //where n is the number of discs. "Peg A" contains all the discs at start and "Peg B" will get all the discs at the end. Recursively, this solution solves the movement of (n-1) discs at each step. This is the basic idea for the solution of the 750 points problem in the practice room of Google CodeJam.

No comments:

Post a Comment

Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.