[转帖] 用C# Generator解决Hanoi塔问题

下面的代码从 Iterators in C#: Nothing Beats the Foreach Loop转来。

using System.Collections.Generic;

public enum Peg { A, B, C };

public struct Move {
    public Move( Peg from, Peg to ) { From = from; To = to; }
    public readonly Peg From;
    public readonly Peg To;
}

class TowerofHanoi {
    public static IEnumerable<Move> GenerateMoves(
        int n, Peg from, Peg to, Peg middle ) {
        if ( n == 1 )
            yield return new Move( from, to );
        else {
            foreach ( Move m in GenerateMoves( n - 1, from, middle, to ) )
                yield return m;

            yield return new Move( from, to );

            foreach ( Move m in GenerateMoves( n - 1, middle, to, from ) )
                yield return m;
        }
    }
}

class Program {
    static void Main( string[ ] args ) {
        foreach ( Move m in
            TowerofHanoi.GenerateMoves( 10, Peg.A, Peg.B, Peg.C ) ) {
            System.Console.WriteLine( "From {0} to {1}", m.From, m.To );
        }
    }
}


以前一直没想过generator可以这样用。能让generator自己递归这点相当让我着迷。
最近支持generator的语言也越来越多了。JavaScript也提供了支持。有意思啊……

程序的输出结果放在附件里了。

你可能感兴趣的:(JavaScript,C++,c,C#)