Advertisement
ArXen42

Hanoi

Apr 7th, 2016
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public class Program
  5. {
  6.     public static void Main(String[] args)
  7.     {
  8.         Hanoi(3);
  9.     }
  10.  
  11.     private static Stack<Int32>[] towers = new Stack<int>[3];
  12.  
  13.     public static void Hanoi(int count)
  14.     {
  15.         ringsCount = count; iterationsCount = 0;
  16.  
  17.         towers[0] = new Stack<int>();
  18.         for (int i = 0; i < count; i++)
  19.             towers[0].Push(count - i);
  20.  
  21.         towers[1] = new Stack<int>();
  22.         towers[2] = new Stack<int>();
  23.  
  24.         Move(count, towers[0], towers[1], towers[2]);
  25.         WriteTowers();
  26.     }
  27.  
  28.     private static int ringsCount, iterationsCount;
  29.  
  30.     private static void Move(int q, Stack<Int32> from, Stack<Int32> to, Stack<Int32> buf)
  31.     {
  32.  
  33.         if (q > 0)
  34.         {
  35.             Move(q - 1, from, buf, to);
  36.  
  37.             WriteTowers();
  38.             iterationsCount++;
  39.  
  40.             int disk = from.Peek();
  41.             from.Pop();
  42.             to.Push(disk);
  43.  
  44.             Move(q - 1, buf, to, from);
  45.         }
  46.     }
  47.  
  48.     private static void WriteTowers()
  49.     {
  50.         var strings = new string[ringsCount];
  51.  
  52.         foreach (var tower in towers)
  53.         {
  54.             int i = 0;
  55.  
  56.             while (i < ringsCount - tower.Count)
  57.             {
  58.                 strings[i] += "|  ";
  59.                 i++;
  60.             }
  61.  
  62.             foreach (int ring in tower)
  63.             {
  64.                 strings[i] += ring.ToString() + "  ";
  65.                 i++;
  66.             }
  67.         }
  68.         Console.WriteLine("ะจะฐะณ โ„– {0}:", iterationsCount);
  69.         foreach (string str in strings)
  70.             Console.WriteLine(str);
  71.  
  72.         Console.WriteLine();
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement