Skip to content

Instantly share code, notes, and snippets.

@Flyrell
Last active June 20, 2020 14:50
Show Gist options
  • Save Flyrell/bfeafae436aa183c9ae18d3cb84b1fb7 to your computer and use it in GitHub Desktop.
Save Flyrell/bfeafae436aa183c9ae18d3cb84b1fb7 to your computer and use it in GitHub Desktop.
Simple function for generating all possible configuration without repeating the items with possibility to specify the output length
function* getAllPossibleCombinations(arr, outputLength = arr.length) {
if (outputLength > arr.length) {
throw 'Not enough items in array';
}
for (let i = 0; i < arr.length; i++) {
if (outputLength === 1) yield arr[i];
for (let j = 0; j < arr.length; j++) {
if (i === j) continue;
const r = arr[i] + arr[j];
if (outputLength <= 2) yield r;
const nextArr = arr.filter((_, index) => index !== i && index !== j);
const iterator = getAllPossibleCombinations(nextArr, outputLength - 2);
yield r + iterator.next().value;
}
}
};
function getAllPossibleCombinations(arr, outputLength = arr.length) {
if (outputLength > arr.length) {
console.warn('Not enough items in array');
return [];
}
let output = [];
for (let i = 0; i < arr.length; i++) {
if (outputLength === 1) {
output.push(arr[i]);
continue;
}
for (let j = 0; j < arr.length; j++) {
if (i === j) continue;
const r = arr[i] + arr[j];
if (outputLength <= 2) {
output.push(r);
continue;
}
const nextArr = arr.filter((_, index) => index !== i && index !== j);
output.push(...getAllPossibleCombinations(nextArr, outputLength - 2).map(comb => r + comb));
}
}
return output;
};
// Usage:
//
// generateAllPossibleCombinations(['a', 'b']);
// output: ['ab', 'ba']
//
// generateAllPossibleCombinations(['a', 'b', 'c'], 2);
// output: ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment