JavaScript - Generating All Combinations of Elements in a Single Array (In Pairs)

Javascript - Generating all combinations of elements in a single array (in pairs)

A simple way would be to do a double for loop over the array where you skip the first i elements in the second loop.

let array = ["apple", "banana", "lemon", "mango"];let results = [];
// Since you only want pairs, there's no reason// to iterate over the last element directlyfor (let i = 0; i < array.length - 1; i++) { // This is where you'll capture that last value for (let j = i + 1; j < array.length; j++) { results.push(`${array[i]} ${array[j]}`); }}
console.log(results);

Javascript - All Possible Combinations From Single Array Every Order

At first create function to find all combinations of array:

function combinations(array) {
return new Array(1 << array.length).fill().map(
(e1, i) => array.filter((e2, j) => i & 1 << j));
}

Then you have to create function to generate all permutations of given array (for example this using Heap's method:

function permute(permutation) {
var length = permutation.length,
result = [permutation.slice()],
c = new Array(length).fill(0),
i = 1, k, p;

while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push(permutation.slice());
} else {
c[i] = 0;
++i;
}
}
return result;
}

After that you can combine that to final function:

function calculateAllCombinations(myArray) {
var allValues = combinations(myArray)

var response = allValues

for(let v of allValues) {
response = response.concat(permute(v))
}

//Return removed duplicates
return Array.from(new Set(response.map(JSON.stringify)), JSON.parse)

}

At the end you can call it like this:

var myArray = ["apple", "banana", "lemon", "mango"]

var allValues = calculateAllCombinations(myArray)

JavaScript - Generating combinations from n arrays with m elements

Here is a quite simple and short one using a recursive helper function:

function cartesian(...args) {
var r = [], max = args.length-1;
function helper(arr, i) {
for (var j=0, l=args[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(args[i][j]);
if (i==max)
r.push(a);
else
helper(a, i+1);
}
}
helper([], 0);
return r;
}

Usage:

cartesian([0,1], [0,1,2,3], [0,1,2]);

To make the function take an array of arrays, just change the signature to function cartesian(args) instead of using rest parameter syntax.



Related Topics



Leave a reply



Submit