0

I just want to get cartesian product of numbers in a single list with specified number in C#. In below, I gave some examples of actually what I want get to:

List<int> numbers = new List<int>() { 0, 1, 2 };

There should be a function to get all cartesian product of that numbers with given number n.

For example, n=2 then the output should be like this:

0,0
0,1
0,2
1,0
1,1
1,2
2,0
2,1
2,2

Are there any suggestions or examples for this?

mrciga
  • 47
  • 8
  • 2
    Use a search engine. http://stackoverflow.com/questions/13647662/generating-a-n-ary-cartesian-product-example – Evan Trimboli Feb 20 '15 at 11:28
  • This function is not built into the language. – Sam Axe Feb 20 '15 at 11:28
  • Thanks for the answers but I should do that with single list and also efficiently. There should be a great solution for that. – mrciga Feb 20 '15 at 11:30
  • Look at Linq SelectMany – tolanj Feb 20 '15 at 11:35
  • To those who marked this dup; question. Is this not more specific to a self-join of one list, and not a product of multiple amount of sets? So though it can be answered by the more generic dup, it has an easier solution being specific as it is. – Edward Feb 26 '17 at 03:33

1 Answers1

2

As long as you only want to create the cartesian product of two sets you can use LINQ SelectMany:

var n = 2;
var numbers = Enumerable.Range(0, n + 1);
var cartesianProduct = numbers.SelectMany(_ => numbers, (a, b) => Tuple.Create(a, b));

When cartesianProduct is enumerated it will generate 9 tuples exactly as you specify in your question.

If you have to create cartesian products of higher dimensions it is better to use recursion.

Community
  • 1
  • 1
Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
  • I am wondering if I use `var a = s.SelectMany(_=>s.Where(z=> z>_), (x,y) => new[]{x,y})` to produce all sets where none of the ints (or numbers) equal and haven't already been represented in reverse (ex. if I have {1,2} I don't need {2,1} ); will this linq/lambda statement be any faster performance wise then two for loops which is O(n^2) ?? – Edward Feb 26 '17 at 03:18
  • 1
    @Edward: LINQ (in this case "LINQ to objects") does not have magic powers. When you enumerate the LINQ expression (in your case `s`) it will execute `SelectMany` as two nested `foreach` loops and the complexity will by `O(n^2)`. In fact, hand writing the loops can lead to slightly more efficient code, not in terms of complexity but in terms of execution time, because you can avoid some allocations. However, for anything but really performance critical code I always prefer LINQ as it allows me to write more compact, reusable and expressive code. – Martin Liversage Feb 26 '17 at 10:51