Skip to content

Instantly share code, notes, and snippets.

@shiv19
Created May 17, 2023 01:51
Show Gist options
  • Save shiv19/fa12a817dc17d8284e8283d96d134967 to your computer and use it in GitHub Desktop.
Save shiv19/fa12a817dc17d8284e8283d96d134967 to your computer and use it in GitHub Desktop.
Generate nCr Combinations for a given set
// Author: ChatGPT
function generateCombinations(set, r) {
const combinations = [];
function generate(currentCombination, remainingSet, r) {
if (currentCombination.length === r) {
combinations.push(currentCombination);
return;
}
if (remainingSet.length < r - currentCombination.length) {
return;
}
for (let i = 0; i < remainingSet.length; i++) {
// Skip duplicates
if (i > 0 && remainingSet[i] === remainingSet[i - 1]) {
continue;
}
const newCombination = currentCombination.concat(remainingSet[i]);
const newSet = remainingSet.slice(i + 1);
generate(newCombination, newSet, r);
}
}
set.sort(); // Sort the set to ensure duplicates are adjacent
generate([], set, r);
return combinations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment