我想用JavaScript进行排列,这是我的代码
const arr = [1, 2, 3, 4, 5];
for (let i1 = 0; i1 < arr.length; i1++) {
for (let i2 = i1 + 1; i2 < arr.length; i2++) {
console.log(arr[i1] + ' ' + arr[i2]);
}
}
https://jsfiddle.net/op51x6mv/1/
该代码的结果:
["1 2", "1 3", "1 4", "1 5", "2 3", "2 4", "2 5", "3 4", "3 5", "4 5"]
我想问一下,为什么排列的所有结果都没有显示?从这些结果中,我没有看到数字
["2 1", "3 1", "3 2", "4 1", "4 2", "4 3", "5 1", "5 2", "5 3", "5 4"]
请告诉我这段代码在哪里出错?或者,如果您有更好的代码,请帮助我。
谢谢
您可以从头到尾循环两次,并省略相同的索引。
const arr = [1, 2, 3, 4, 5];
for (let i1 = 0; i1 < arr.length; i1++) {
for (let i2 = 0; i2 < arr.length; i2++) {
if (i1 === i2) continue;
console.log(arr[i1] + ' ' + arr[i2]);
}
}
您想要的是...从数学上讲...不是排列,而是没有重复的变化(但这实际上无关紧要。)>
I wrote a code for this in PHP a bit earlier,这是它的JS变体(选择给定数量的元素,可以处理数据中的重复等):
const variations = (arr, n = arr.length) => {
if(n === 0) return [[]]
if(!(n >= 0)) return []
const output = []
for(let i = 0; i < arr.length; i++){
if(arr.indexOf(arr[i]) < i) continue
const newArr = arr.slice()
newArr.splice(i, 1)
output.push(...variations(newArr, n - 1).map(e => [arr[i], ...e]))
}
return output
}
const arr = [1, 2, 3, 4, 5];
console.log(variations(arr, 2))
//If you want to concatenate them, use:
console.log(variations(arr, 2).map(e => e.join(' ')))