Skip to content

Instantly share code, notes, and snippets.

@GeneralD
Created August 10, 2018 16:19
Show Gist options
  • Save GeneralD/cf0cd9187ec0c53aeaf0662be5193ac3 to your computer and use it in GitHub Desktop.
Save GeneralD/cf0cd9187ec0c53aeaf0662be5193ac3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hanoi {
class HanoiTower {
static void Main(string[] args) {
int height;
if (args.Length == 0 || !int.TryParse(args[0], out height)) height = 3;
var count = 0;
foreach (var towers in new HanoiTower(height).Resolve()) Console.WriteLine("\n=== STEP: {0} ===\n{1}", ++count, towers.Select(i => i.Reverse().Aggregate("|", (l, r) => l + r + "|")).Aggregate((l, r) => l + "\n" + r));
}
private readonly Stack<int> sourceTower = new Stack<int>();
private readonly Stack<int> bareTower = new Stack<int>();
private readonly Stack<int> destinationTower = new Stack<int>();
public HanoiTower(int height) => Enumerable.Range(0, height).Select(i => height - i).ToList().ForEach(sourceTower.Push);
private IEnumerable<Stack<int>[]> Resolve() => Resolve(sourceTower.Count(), sourceTower, bareTower, destinationTower);
private IEnumerable<Stack<int>[]> Resolve(int height, params Stack<int>[] towers) {
if (height > 1) foreach (var ret in Resolve(height - 1, towers[0], towers[2], towers[1])) yield return ret;
towers[2].Push(towers[0].Pop());
yield return new[] { sourceTower, bareTower, destinationTower };
if (height > 1) foreach (var ret in Resolve(height - 1, towers[1], towers[0], towers[2])) yield return ret;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment