Solving the Towers of Hanoi puzzle in C#

I thought this would be a fun little exercise to try. This puzzle is generally used to teach recursion in CS classes, but I have never actually tried to implement it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TowersOfHanoiCs
{
    class Program
    {
        static List peg1;
        static List peg2;
        static List peg3;

        static void Main(string[] args)
        {
            peg1 = new List();
            peg2 = new List();
            peg3 = new List();

            for (int i = 1; i < 8; i++)
            {
                peg1.Add(i);
            }

            Display();
            MoveDisk(7, peg1, peg2, peg3);
            Console.ReadLine();
        }

        static void MoveDisk(int disk, List source, List destination, List temp)
        {
            int position = source.IndexOf(disk);

            if (position == 0)
            {
                source.Remove(disk);
                destination.Insert(0, disk);
                Display();
            }
            else
            {
                int nextDisk = source[position - 1];
                MoveDisk(nextDisk, source, temp, destination);
                MoveDisk(disk, source, destination, temp);
                MoveDisk(nextDisk, temp, destination, source);
            }
        }

        static void Display()
        {
            DisplayPeg(peg1);
            DisplayPeg(peg2);
            DisplayPeg(peg3);
            Console.WriteLine("----------");
        }

        static void DisplayPeg(List peg)
        {
            foreach (int x in peg)
            {
                Console.Write(x + " ");
            }
            Console.WriteLine();
        }
    }
}

Leave a Reply