| Schultz's profileSchultzpacePhotosBlogNetwork | Help |
|
May 02 Tower of Hanoi in C#using System; using System.Collections.Generic; using System.Text;
namespace Hanoi { class Program { static void Main(string[] args) { int count = 3; if (args.Length != 0 && !Int32.TryParse(args[0], out count)) { count = 3; }
for (int i = 0; i < 3; i++) { pinsAndDisks[i] = new Stack<int>(); }
for (int i = 0; i < count; i++) { pinsAndDisks[0].Push(count - i); }
Hanoi(0, 2, 1, count);
Console.WriteLine("Total number of calls: {0}.", depth); }
static int depth; static Stack<int>[] pinsAndDisks = new Stack<int>[3];
static void Hanoi(int source, int dest, int misc, int count) { depth++;
if (count == 1) { MoveAndPrint(source, dest); } else { Hanoi(source, misc, dest, count - 1); MoveAndPrint(source, dest); Hanoi(misc, dest, source, count - 1); } }
static void MoveAndPrint(int source, int dest) { int disk = pinsAndDisks[source].Pop(); pinsAndDisks[dest].Push(disk); for (int pin = 0; pin < 3; pin++) { if (pinsAndDisks[pin].Count == 0) { Console.WriteLine("|-----"); } else { string pinView = ""; Stack<int>.Enumerator e = pinsAndDisks[pin].GetEnumerator(); while (e.MoveNext()) { pinView = e.Current + "-" + pinView; } Console.WriteLine("|-" + pinView); } } Console.WriteLine(); } } }
Comments (1)
TrackbacksThe trackback URL for this entry is: http://schultz9999.spaces.live.com/blog/cns!CF947AA877D8D439!242.trak Weblogs that reference this entry
|
|
|