Calculating all possible sub-sequences of a given length (C#)

前端 未结 4 1404
悲&欢浪女
悲&欢浪女 2020-12-16 06:21

If I have a sequence as follows (let\'s say it\'s an IEnumerable):

[A, B, C, D, E]

Then what\'s the cleanest way to c

4条回答
  •  一整个雨季
    2020-12-16 07:25

    I've had success with IanG's PermuteUtils class:

    char[] items = new char[] { 'A', 'B', 'C', 'D', 'E' };
    
    foreach (IEnumerable permutation in PermuteUtils.Permute(items, 3)) {
        Console.Write("[");
        foreach (char c in permutation) {
            Console.Write(" " + c);
        }
        Console.WriteLine(" ]");
    }
    

    Results in:

    [ A B C ]
    [ A B D ]
    [ A B E ]
    [ A C B ]
    [ A C D ]
    [ A C E ]
    [ A D B ]
    [ A D C ]
    [ A D E ]
    [ A E B ]
    [ A E C ]
    [ A E D ]
    [ B A C ]
    [ B A D ]
    [ B A E ]
    [ B C A ]
    [ B C D ]
    [ B C E ]
    [ B D A ]
    [ B D C ]
    ...
    

提交回复
热议问题