Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- namespace Tower_of_Hanoi
- {
- class Program
- {
- public static Stack<Int32> towerA = null, towerB = null, towerC = null;
- public static int intTotalMoves = 0;
- public static int speed;
- static void Main(string[] args)
- {
- int numDiscs;
- Console.Write("Enter the number of disc: ");
- numDiscs = int.Parse(Console.ReadLine());
- Console.Write("Enter the speed of solving from 1(slowest) to 10(fastest): ");
- speed = int.Parse(Console.ReadLine());
- speed = (10 - speed) * 100;
- Init(numDiscs, ref towerA, ref towerB, ref towerC);
- print(towerA, towerB, towerC);
- /* Start Game */
- //Move nDisks from towerA to TowerC using towerB as a placeholder
- move(towerA.Count, towerA, towerC, towerB);
- Console.WriteLine("\n\nTotal moves made " + intTotalMoves);
- Console.ReadLine();
- }
- static void move(int nDiscs, Stack<Int32> from, Stack<Int32> to, Stack<Int32> temp)
- {
- //Base Case
- if(nDiscs == 1)
- {
- //Directly move it to the destination
- to.Push(from.Pop());
- intTotalMoves++;
- print(towerA, towerB, towerC);
- Thread.Sleep(speed);
- return;
- }
- move(nDiscs - 1, from, temp, to);
- move(1, from, to, temp);
- move(nDiscs - 1, temp, to, from);
- }
- static void print(Stack<Int32> towerA, Stack<Int32> towerB, Stack<Int32> towerC)
- {
- /* Reverse the stacks for ease of printing */
- towerA = new Stack<Int32>(towerA);
- towerB = new Stack<Int32>(towerB);
- towerC = new Stack<Int32>(towerC);
- Console.Write("Tower A: ");
- while(towerA.Count != 0)
- Console.Write(towerA.Pop().ToString());
- Console.WriteLine();
- Console.Write("Tower B: ");
- while (towerB.Count != 0)
- Console.Write(towerB.Pop().ToString());
- Console.WriteLine();
- Console.Write("Tower C: ");
- while (towerC.Count != 0)
- Console.Write(towerC.Pop().ToString());
- Console.WriteLine("\n");
- }
- static void Init(int numDisks, ref Stack<Int32> towerA, ref Stack<Int32> towerB, ref Stack<Int32> towerC)
- {
- towerA = new Stack<int>();
- towerC = new Stack<int>();
- towerB = new Stack<int>();
- for (int i = numDisks; i >= 1; i--)
- towerA.Push(i);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement