Created
April 23, 2012 13:13
-
-
Save mnzk/2470838 to your computer and use it in GitHub Desktop.
ExPermutations.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
static class Ex { | |
public static IEnumerable<IEnumerable<T>> RotationsL<T>(this IEnumerable<T> xs) { | |
for(int i = xs.Count(); i > 0; i--) { | |
yield return xs; | |
xs = xs.Concat(xs.Take(1)).Skip(1); | |
} | |
} | |
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> xs) { | |
if(xs.Count() == 0) yield return Enumerable.Empty<T>(); | |
foreach(var ys in xs.RotationsL()) { | |
var zs = ys.Take(1); | |
foreach(var ws in ys.Skip(1).Permutations()) { | |
yield return zs.Concat(ws); | |
} | |
} | |
} | |
} | |
// 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