Skip to content

Instantly share code, notes, and snippets.

@mnzk
Created April 24, 2012 14:19
Show Gist options
  • Save mnzk/2480053 to your computer and use it in GitHub Desktop.
Save mnzk/2480053 to your computer and use it in GitHub Desktop.
ExPermutations2.cs
// 辞書順で順列列挙
using System;
using System.Linq;
using System.Collections.Generic;
static class Ex {
private static IEnumerable<IEnumerable<T>[]> __MoveRtoL<T>(IEnumerable<T> e1, IEnumerable<T> e2) {
while(e2.Count() > 0) {
yield return new IEnumerable<T>[]{e1, e2};
e1 = e1.Concat(e2.Take(1));
e2 = e2.Skip(1);
}
}
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> xs) {
if(xs.Count() == 0) yield return Enumerable.Empty<T>();
foreach(var ea in __MoveRtoL(Enumerable.Empty<T>(), xs)) {
var ys = ea[1].Take(1);
foreach(var zs in ea[0].Concat(ea[1].Skip(1)).Permutations()) {
yield return ys.Concat(zs);
}
}
}
}
// Examples
class Program {
public static void Main(string[] args) {
foreach(var xs in Enumerable.Range(1,3).Permutations()) {
Console.WriteLine(string.Join("-", xs.Select(x=>x.ToString()).ToArray()));
}
foreach(var xs in "ABCD".Permutations()) {
Console.WriteLine(string.Join("-", xs.Select(x=>x.ToString()).ToArray()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment