Created
May 17, 2023 01:51
-
-
Save shiv19/fa12a817dc17d8284e8283d96d134967 to your computer and use it in GitHub Desktop.
Generate nCr Combinations for a given set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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