Advertisement
gabi11

Algorithms - 04. Towers of Hanoi

Sep 7th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Algorithms
  6. {
  7.     class Program
  8.     {
  9.         private static int steps = 0;
  10.         private static Stack<int> source;
  11.         private static Stack<int> destination;
  12.         private static Stack<int> spare;
  13.         static void Main(string[] args)
  14.         {
  15.             int n = int.Parse(Console.ReadLine());
  16.  
  17.             var range = Enumerable.Range(1, n).Reverse();
  18.             source = new Stack<int>(range);
  19.             destination = new Stack<int>();
  20.             spare = new Stack<int>();
  21.  
  22.             PrintRods();
  23.             MoveDisks(n, source, spare, destination);
  24.         }
  25.  
  26.         private static void MoveDisks(int bottomDisk, Stack<int> sourceRod, Stack<int> spareRod, Stack<int> destinationRod)
  27.         {
  28.             if (bottomDisk == 1)
  29.             {
  30.                 steps++;
  31.                 destinationRod.Push(sourceRod.Pop());
  32.                 Console.WriteLine($"Step #{steps}: Moved disk");
  33.                 PrintRods();
  34.                 return;
  35.             }
  36.  
  37.             MoveDisks(bottomDisk - 1, sourceRod, destinationRod, spareRod);
  38.             destinationRod.Push(sourceRod.Pop());
  39.             steps++;
  40.             Console.WriteLine($"Step #{steps}: Moved disk");
  41.             PrintRods();
  42.             MoveDisks(bottomDisk - 1, spareRod, sourceRod, destinationRod);
  43.         }
  44.  
  45.         private static void PrintRods()
  46.         {
  47.             Console.WriteLine($"Source: {string.Join(", ", source.Reverse())}");
  48.             Console.WriteLine($"Destination: {string.Join(", ", destination.Reverse())}");
  49.             Console.WriteLine($"Spare: {string.Join(", ", spare.Reverse())}");
  50.             Console.WriteLine();
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement