I try to write a LINQ statement which returns me all possible combinations of numbers (I need this for a test and I was inspired by this article of Eric Lippert). The method's prototype I call looks like:
IEnumerable<Collection<int>> AllSequences( int start, int end, int size );
The rules are:
size
start
and end
should be usedSo calling the AllSequences( 1, 5, 3 )
should result in 10 collections, each of size 3:
1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5
Now, somehow I'd really like to see a pure LINQ solution. I am able to write a non LINQ solution on my own, so please put no effort into a solution without LINQ.
My tries so far ended at a point where I have to join a number with the result of a recursive call of my method - something like:
return from i in Enumerable.Range( start, end - size + 1 ) select BuildCollection(i, AllSequences( i, end, size -1));
But I can't manage it to implement BuildCollection()
on a LINQ base - or even skip this method call. Can you help me here?
What about this? IEnumerable<int> range = Enumerable. Range(1, 20); IEnumerable<int> banned = Enumerable. Range(15, 4); return range.
Enumerable.Range(1, 12) .Select(x => (x - 1) + 1);
Think I've got it.
IEnumerable<List<int>> AllSequences(int start, int end, int size) { if (size == 0) return Enumerable.Repeat<List<int>>(new List<int>(), 1); return from i in Enumerable.Range(start, end - size - start + 2) from seq in AllSequences(i + 1, end, size - 1) select new List<int>{i}.Concat(seq).ToList(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With