Is it possible to create some Linq that generates a list containing all possible combinations of a series of numbers?
If you enter "21", it will generate a list with elements:
list[0] = "21" list[1] = "22" list[2] = "11" list[3] = "12"
(Not necessarily in that order)
I understand that you can use a range to do things like:
List<char> letterRange = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToList();
What generates the alphabet from az. But I can not transfer this knowledge to create a combination generator
I was able to figure out the following code, but it seems too cumbersome, and I'm sure it can be done with a few lines. It really seems like the bad decision I made.
Imagine what I called GetAllCombinations("4321") if it helps
public static String[] GetAllCombinations(String s) { var combinations = new string[PossibleCombinations(s.Length)]; int n = PossibleCombinations(s.Length - 1); for (int i = 0; i < s.Length; i++) { String sub; String[] subs; if (i == 0) { sub = s.Substring(1); //Get the first number } else if (i == s.Length - 1) { sub = s.Substring(0, s.Length - 1); } else { sub = s.Substring(0, i) + s.Substring(i + 1); } subs = GetAllCombinations(sub); for (int j = 0; j < subs.Length; j++) { combinations[i * n + j] = s[i] + subs[j]; } } return combinations; } public static int PossibleCombinations(int n) //Combination possibilities. eg 1-2-3-4 have 24 different combinations { int result = 1; for (int i = 1; i <= n; i++) result *= i; return result; }
c # linq combinations
CasperT Apr 21 '09 at 20:30 2009-04-21 20:30
source share