[Solved] List Combinations c#


Visual Studio was taking too long to load, so I did it in JavaScript since I could test in my console. This will print out all the choices. (Also it sounds more like a “what’s the algorithm for this?” not “what’s the algorithm for this in C#?”)

function makeGroup(id, count) {
  var result = [];
  for (var i = 1; i <= count; i++) {
    result.push(id + i);
  }
  return result;
}

function choose(group, count) {
  if (count === 1) {
    var result = [];
    for (var i = 0; i < group.length; i++) {
      result.push([group[i]]);
    }
    return result;
  }
  if (count === 2) {
    var result = [];
    for (var i = 0; i < group.length; i++) {
      for (var j = 0; j < group.length; j++) {
        if (i !== j && 
            i < j) {
          result.push([group[i], group[j]]);
        }
      }
    }
    return result;
  }
  if (count === 3) {
    var result = [];
    for (var i = 0; i < group.length; i++) {
      for (var j = 0; j < group.length; j++) {
        for (var k = 0; k < group.length; k++) {
          if (i !== j && i !== k && j !== k &&
              i < j && j < k) {
            result.push([group[i], group[j], group[k]]);
          }
        }
      }
    }
    return result;
  }
}

var groupA = makeGroup('A', 2);
var groupB = makeGroup('B', 2);
var groupC = makeGroup('C', 3);
var groupD = makeGroup('D', 1);

choose(groupA, 1).forEach(function (a) { 
  choose(groupB, 2).forEach(function (b) {
    choose(groupC, 3).forEach(function (c) {
      choose(groupD, 1).forEach(function (d) {
        console.log(a + " " + b[0] + " " + b[1] + " " + c[0] + " " + c[1] + " " + c[2] + " " + d[0]);
      });
    });
  });
});

Example output:

A1 B1 B2 C1 C2 C3 D1
A2 B1 B2 C1 C2 C3 D1

To see an example of it working, you can do:

var testGroup = makeGroup('T', 4);

var choose1 = choose(testGroup, 1);
var choose2 = choose(testGroup, 2);
var choose3 = choose(testGroup, 3);

console.log(JSON.stringify(choose1));
console.log(JSON.stringify(choose2));
console.log(JSON.stringify(choose3));

And see that it chooses correctly:

[["T1"],["T2"],["T3"],["T4"]]
[["T1","T2"],["T1","T3"],["T1","T4"],["T2","T3"],["T2","T4"],["T3","T4"]]
[["T1","T2","T3"],["T1","T2","T4"],["T1","T3","T4"],["T2","T3","T4"]]

0

solved List Combinations c#