Created
June 28, 2014 15:16
-
-
Save loosechainsaw/524431917e1f6e3de2a8 to your computer and use it in GitHub Desktop.
C# Permutation Generator
This file contains hidden or 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.Collections.Generic; | |
using System.Linq; | |
using System.Collections; | |
using System.Text; | |
namespace CSharpPermutations | |
{ | |
public interface IPermutable<T> | |
{ | |
ISet<T> GetRange(); | |
} | |
public class Digits : IPermutable<int> | |
{ | |
public ISet<int> GetRange() | |
{ | |
ISet<int> set = new HashSet<int>(); | |
for (int i = 0; i < 10; ++i) | |
set.Add(i); | |
return set; | |
} | |
} | |
public class AlphaNumeric : IPermutable<char> | |
{ | |
public ISet<char> GetRange() | |
{ | |
ISet<char> set = new HashSet<char>(); | |
set.Add('0'); | |
set.Add('1'); | |
set.Add('2'); | |
set.Add('3'); | |
set.Add('4'); | |
set.Add('5'); | |
set.Add('6'); | |
set.Add('7'); | |
set.Add('8'); | |
set.Add('9'); | |
set.Add('a'); | |
set.Add('b'); | |
return set; | |
} | |
} | |
public class PermutationGenerator<T,P> : IEnumerable<string> | |
where P : IPermutable<T>, new() | |
{ | |
public PermutationGenerator(int number) | |
{ | |
this.number = number; | |
this.range = new P().GetRange(); | |
} | |
public IEnumerator<string> GetEnumerator() | |
{ | |
foreach (var item in Permutations(0,0)) | |
{ | |
yield return item.ToString(); | |
} | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
foreach (var item in Permutations(0,0)) | |
{ | |
yield return item; | |
} | |
} | |
private IEnumerable<StringBuilder> Permutations(int n, int k) | |
{ | |
if (n == number) | |
yield return new StringBuilder(); | |
foreach (var element in range.Skip(k)) | |
{ | |
foreach (var result in Permutations(n + 1, k + 1)) | |
{ | |
yield return new StringBuilder().Append(element).Append(result); | |
} | |
} | |
} | |
private int number; | |
private ISet<T> range; | |
} | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
foreach (var element in new PermutationGenerator<char, AlphaNumeric>(2)) | |
{ | |
Console.WriteLine(element); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment