C# generic permutation, ordered sub sets with Linq
Purpose
This article introduces two pieces of C# code that may be useful for math riddles and learning c# and linq.
GetPermutations
Takes any set as input, and will output all possible orders or the input set.
Second argument: Length of output sets: Usually you will specify the output sets the have the same length as the input set. You may also specify to get permutations of shorter output sets.
See https://en.wikipedia.org/wiki/Permutation
Be aware the the number of output sets can get very large very fast: Number of output sets is the factorial n! of the size of the input set.
Size of input set | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|
Number of permutations | 1 | 2 | 6 | 24 | 120 | 720 | 5040 | 40320 |
Code
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) != 0)), (t1, t2) => t1.Concat(new T[] { t2 }));
}
GetOrderedSubSets
Takes any set as input, and will output all subsets where elements are in the same order as input set.
Second argument: Length of the output sets. Usually this will be smaller then length of input set.
Example input set: {"a", "b", "c"}, Length = 2.
Then the output sets will be {"a", "b"}, {"a", "c"}, {"b", "c"}
Code
public static IEnumerable<IEnumerable<T>> GetOrderedSubSets<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetOrderedSubSets(list, length - 1).SelectMany(t => list.Where(e => t.All(g => g.CompareTo(e) == -1)), (t1, t2) => t1.Concat(new T[] { t2 }));
}
More
If you really want to get into it, reading might not be enough. Start your favorite c# dev environment and play around with it. Create some examples and display the output. Try to make the code more beautiful and easier to understand using your own coding style preferences. If you are looking for related math riddles: http://www.primepuzzles.net E.g. puzzle 929 uses GetOrderedSubSets.
Congratulations @simondev! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Congratulations @simondev! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!