2

I couldn't find it anywhere and I'm not sure if this is even possible but is there a way to get every unique number combination regardless of the digit placement (so for example 123, 213, 231, 321 are all one combination because they have the same numbers but 123 and 124 are different) so every possible combination for X amount of digits.. thanks!

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • I think that your question regards more maths than programming https://en.wikipedia.org/wiki/Combination – Francesco Jun 24 '20 at 14:59

1 Answers1

1

Here's a code I wrote once:

function kPn(k, values, repetition) {
  var retVal=[];
  var n=(Array.isArray(values))?n=values.length:values;
  var list=[];
  for(var i=0;i<n;i++) {
    list.push(i);
    retVal.push([i]);
  }
  for(var i=2;i<=k;i++) {
    var tempRetVal=[];
    for(var rv=0;rv<retVal.length;rv++)
      for(var l=0;l<list.length;l++) {
        if(repetition||!(retVal[rv].includes(list[l]))) {
          var retValItem=retVal[rv].slice();
          retValItem.push(list[l]);
          tempRetVal.push(retValItem);
        }
      }
    retVal=tempRetVal;
  }
  if(!Array.isArray(values)) values=list;
  var permutations=retVal;
  var retVal=[];
  for(var i=0;i<permutations.length;i++) {
    tempSet=[];
    for(var j=0;j<permutations[i].length;j++)
      tempSet.push(values[permutations[i][j]]);
    retVal.push(tempSet);
  }
  return retVal;
}

k: how many values you want,
values: array of values, and
repetition: true|flase.

example:

kPn(3, ["a","b","c"], false);

returns:

(6) [Array(3), Array(3), Array(3), Array(3), Array(3), Array(3)]
0: (3) ["a", "b", "c"]
1: (3) ["a", "c", "b"]
2: (3) ["b", "a", "c"]
3: (3) ["b", "c", "a"]
4: (3) ["c", "a", "b"]
5: (3) ["c", "b", "a"]
length: 6
__proto__: Array(0)
iAmOren
  • 2,760
  • 2
  • 11
  • 23