I have a situation where I need to convert a random array of whole numbers of an unknown length, to multiple pairs of 2.
Ex:
var numbers = [1, 5, 0, 7, 5, 5, 1, 7, 5, 1, 2, 1];
-----------------------------------------------------
[[1, 5], [0, 7], [5, 5], [1, 7], [5, 1], [2, 1]]
There are a few constraints that need to follow, such as:
- There should be exactly 6 pairs (each of 2 numbers).
- If there aren't enough numbers in the
numbersarray to make 6 pairs, then generate a number that is between 1-9. - Each item in the
numbersarray can be used only once. - Each pair must be unique. But e.g
[1,2]and[2,1]can be considered different pairs. - A pair cannot contain
[0, 0]
So far, I found a function that can find combinations but it does not ignore an index once it has already used it.
var numbers = [1, 5, 0, 7, 5, 5, 1, 7, 5, 1, 2, 1];
function p(t, i) {
if (t.length === 2) {
result.push(t);
return;
}
if (i + 1 > numbers.length) {
return;
}
p(t.concat(numbers[i]), i + 1);
p(t, i + 1);
}
var result = [];
p([], 0);
console.log(result);
What should I do next?