Skip to content

Instantly share code, notes, and snippets.

@omega-takai
Created August 23, 2020 08:21
Show Gist options
  • Select an option

  • Save omega-takai/e8f82f7cb3a09516472b49a614196ce5 to your computer and use it in GitHub Desktop.

Select an option

Save omega-takai/e8f82f7cb3a09516472b49a614196ce5 to your computer and use it in GitHub Desktop.
順列(Permutation)
const alphabetRaw = [
...'あいうえおかきくけこさしすせそたちつてとなにぬねの',
...'はひふへほまみむめもやゆよらりるれろわをん',
]
console.log(alphabetRaw)
// ["あ", "い", "う", "え", "お", "か", "き", "く", "け", "こ", "さ", "し", "す", "せ", "そ", "た", "ち", "つ", "て", "と", "な", "に", "ぬ", "ね", "の", "は", "ひ", "ふ", "へ", "ほ", "ま", "み", "む", "め", "も", "や", "ゆ", "よ", "ら", "り", "る", "れ", "ろ", "わ", "を", "ん"]
function permuteWithRepetitions(permutationOptions, permutationLength = 1) {
if (permutationLength === 1) {
return permutationOptions.map((permutationOption) => [permutationOption])
}
// Init permutations array.
const permutations = []
// Get smaller permutations.
const smallerPermutations = permuteWithRepetitions(
permutationOptions,
permutationLength - 1
)
// Go through all options and join it to the smaller permutations.
permutationOptions.forEach((currentOption) => {
smallerPermutations.forEach((smallerPermutation) => {
permutations.push([currentOption].concat(smallerPermutation).join(''))
})
})
return permutations
}
permuteWithRepetitions(alphabetRaw)
// ["あ"]
// ["い"]
// ["う"]
// ["え"]
// ["お"]
// ["か"]
// ["き"]
// ["く"]
// ["け"]
// ["こ"]
// ["さ"]
// ["し"]
// ["す"]
// ["せ"]
// ["そ"]
// ["た"]
// ["ち"]
// ["つ"]
// ["て"]
// ["と"]
// ["な"]
// ["に"]
// ["ぬ"]
// ["ね"]
// ["の"]
// ["は"]
// ["ひ"]
// ["ふ"]
// ["へ"]
// ["ほ"]
// ["ま"]
// ["み"]
// ["む"]
// ["め"]
// ["も"]
// ["や"]
// ["ゆ"]
// ["よ"]
// ["ら"]
// ["り"]
// ["る"]
// ["れ"]
// ["ろ"]
// ["わ"]
// ["を"]
// ["ん"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment