Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate number sequences with LINQ

Tags:

c#

linq

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:

  • all returned collections have a length of size
  • number values within a collection have to increase
  • every number between start and end should be used

So 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?

like image 370
tanascius Avatar asked Apr 29 '10 12:04

tanascius


People also ask

How do you find the range of a number in C#?

What about this? IEnumerable<int> range = Enumerable. Range(1, 20); IEnumerable<int> banned = Enumerable. Range(15, 4); return range.


2 Answers

 Enumerable.Range(1, 12)            .Select(x => (x - 1) + 1); 
like image 109
Bilal Avatar answered Sep 18 '22 06:09

Bilal


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(); } 
like image 27
Fede Avatar answered Sep 20 '22 06:09

Fede