Created
July 27, 2022 09:58
-
-
Save tudormunteanu/29a82c848b434f5eb1cde5bb2eb64252 to your computer and use it in GitHub Desktop.
Combinations of strings up to a certain number of elements
This file contains 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
export default function combinations(items: Array<string>, items_length: number, n: number): Array<string> { | |
const result = []; | |
const getCombinations = (x, n, m = []) => { | |
if (n <= 0) { | |
return m | |
} | |
for (var i = 0; i < items_length; i++) { | |
const value = getCombinations(x, n - 1, [...m, items[i]]); | |
const hasDuplicates = (arr) => arr.length !== new Set(arr).size; | |
if (!hasDuplicates(value)) { | |
result.push(value); | |
} | |
} | |
return m; | |
} | |
getCombinations(items.length, n); | |
return result.filter(items => items.length == n); | |
} |
This file contains 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
import combinations from '@/utils/combinations'; | |
SEO_TERMS = ["a", "b", "c", "d", "e"] | |
combinations(SEO_TERMS, SEO_TERMS.length, 1) | |
combinations(SEO_TERMS, SEO_TERMS.length, 2) | |
combinations(SEO_TERMS, SEO_TERMS.length, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment