Skip to content

Instantly share code, notes, and snippets.

@0xlkda
Created July 2, 2021 11:23
Show Gist options
  • Save 0xlkda/a1eb6f861fb0656ac7c6c28eefe0f8b8 to your computer and use it in GitHub Desktop.
Save 0xlkda/a1eb6f861fb0656ac7c6c28eefe0f8b8 to your computer and use it in GitHub Desktop.
const getAllCombinations = (arraysToCombine) => {
const divisors = [];
let permsCount = 1;
for (let i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
permsCount *= (arraysToCombine[i].length || 1);
}
const getCombination = (n, arrays, divisors) => arrays.reduce((acc, arr, i) => {
acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);
return acc;
}, []);
const combinations = [];
for (let i = 0; i < permsCount; i++) {
combinations.push(getCombination(i, arraysToCombine, divisors));
}
return combinations;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment