Skip to content

Instantly share code, notes, and snippets.

@pete-otaqui
Created July 12, 2017 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pete-otaqui/61aa2de373f43a535d1fb40e5b0092ea to your computer and use it in GitHub Desktop.
Save pete-otaqui/61aa2de373f43a535d1fb40e5b0092ea to your computer and use it in GitHub Desktop.
Combinations and Pairs in javascript
const _ = require('lodash');
function getPairs(arr) {
let rCount = 0;
const results = arr.map(i => [i]);
const f = (base, rest) => {
for (let i = 0, max = rest.length; i < max; i += 1) {
const entry = [base, rest[i]];
results.push(entry);
}
const recurseRest = rest.slice(1);
if (recurseRest.length) {
f(rest[0], recurseRest);
}
}
f(arr[0], arr.slice(1));
return results;
}
function log(index, ...props) {
let prefix = '';
while (prefix.length < index) prefix += '.';
console.log.apply(console, [prefix].concat(props));
}
function getCombinations(arr) {
let rCount = 0;
// create results, including the initial entries as single-item arrays
const results = arr.map(i => [i]);
// recursion function, takes a base entry and a list of others to include
const f = (base, rest) => {
// loop over each of the `rest`, appending a shortening list of them,
// concatenated to `[base]`
rest.forEach((entry, index) => {
results.push(base.concat(rest.slice(0, rest.length - index)));
})
// if we have enough in `rest`, then do the recursion
if (rest.length > 1) f(base, rest.slice(1));
}
// kick off the recursion once for each entry
arr.forEach((entry, index, full) => {
// don't bother with the last entry - it was added earlier, and will not
// need any further concatenation
if (index === full.length - 1) return;
// go!
f([entry], full.slice(index + 1));
});
// return the final set of results
return results;
}
const topLevels = ["Country", "Division", "Industry", "Juliet", "Kilo", "Lima"];
const allCombinations = getCombinations(topLevels);
const sortedCombinations = _.orderBy(allCombinations, (item) => {
return item.join('');
});
console.log(sortedCombinations);
console.log(sortedCombinations.length);
const allPairs = getPairs(topLevels);
const sortedPairs = _.orderBy(allPairs, (item) => {
return item.join('');
});
console.log(sortedPairs);
console.log(sortedPairs.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment