1

i need to iterate an array of x numbers in given order and calculate all possible combinations, for example:

I have this Array of 5 numbers [01,02,03,04,05], this is the condition to calculate the combinations:

enter image description here

expected output:

01 02 01 03 01 04 01 05 05 04 05 03 05 02 04 03 04 02 03 02

Example of array of 6 numbers [00,00,00,10,40,60], this is the condition to calculate the combinations:

enter image description here

expected output:

00 00 00 00 00 10 00 40 00 60 60 40 60 10 60 00 60 00 00 00 00 10 00 40 40 10 40 00 00 10

so the array can be from length 3 to x length.

this is what i have

function calculate(numbers){
    let combinations = [];
    if(numbers.length == 2){
      combinations = [numbers[0] + ' '+ numbers[1]];
    }else{
      for(let i = 1; i < numbers.length; i++){
        combinations.push(numbers[0] + ' '+ numbers[i]);
      }
      for(let i =  numbers.length - 1; i  >= 1; i--){
        combinations.push(numbers[numbers.length - 1] + ' '+ numbers[i]);
      }
      
    }
    return combinations
  }

let numbers = [01,02,03,04,05];
console.log(calculate(numbers))

thanks in advance

  • 1
    Try to make the example as *small* as possible to make it easier for people to read – MrMythical Sep 08 '21 at 02:11
  • An infinite length input is apt to take an unacceptable amount of time to produce a result. :-) – danh Sep 08 '21 at 02:11
  • Does this answer your question? [Javascript - Generating all combinations of elements in a single array (in pairs)](https://stackoverflow.com/questions/43241174/javascript-generating-all-combinations-of-elements-in-a-single-array-in-pairs) – kmoser Sep 08 '21 at 04:31

3 Answers3

0

I recreated the first example you gave in a more efficient manner, this also greatly simplifies the code: enter image description here

Now for the code

const data = ["01", "02", "03", "04", "05"];

const possibilities = [];

for (let i = 0; i < data.length; i++) {
  let j = i + 1;

  while (j < data.length) {
    possibilities.push(data[i] + " " + data[j]);
    j++;
  }
}

console.log(possibilities);
Ameer
  • 1,980
  • 1
  • 12
  • 24
0
nums.slice(0, nums.length-1).map(
  (n, i) => nums.slice(i+1).map(
    sn => `${n} ${sn}`
  ).join(' ')
).join(' ')

Hope it is what you want.

Silo QIAN
  • 60
  • 8
0

The way you connect the numbers made you think over complicated. If you connect them in this way, then the logic to get all possible combinations is simple. i.e. for each number, pair with every numbers after it. That's all.

enter image description here

const numbers = [1,2,3,4,5];
let combinations = [];
for(let i = 0 ; i < numbers.length; i++)
{
  for(let j = i+1; j < numbers.length; j++)
  {
    combinations.push([numbers[i],numbers[j]]);
  }
}
console.log(combinations);
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30