【发布时间】:2019-05-22 08:44:42
【问题描述】:
我试图找到这样的 2 个数组的每个排列:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords = {
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
}
它应该与 3 个以上的项目一起工作,两个数组的长度总是相同的。这是我的代码:
const keywords = {}
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount) {
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
}
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount) {
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
}
结果少了一些
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
【问题讨论】:
-
在您想要的答案中,第 3 次和第 9 次重复。
-
@Tigger 不,这些是 2 的组合,我需要每个项目的排列
-
@JackOfAshes-MohitGawande 是的,这是一个错误
-
您不是在寻找排列(与顺序有关),而是寻找
[one, ONE]、[two, TWO]和[three, THREE]的cartesian product。你可以通过转置你的输入来获得这些。 -
@Bergi 我不确定您的建议是否适用于任意输入(请参阅我在 Nina Scholz 的回答下的评论)。
标签: javascript algorithm