问题
I want to make permutation with javascript, this is my code
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/
result from that code:
["1 2", "1 3", "1 4", "1 5", "2 3", "2 4", "2 5", "3 4", "3 5", "4 5"]
I want to ask, why are all the results from the permutation not displayed? From these results I did not see the numbers
["2 1", "3 1", "3 2", "4 1", "4 2", "4 3", "5 1", "5 2", "5 3", "5 4"]
please tell Me where the error from this code? or if You have a better code please help Me.
Thank you
回答1:
You could loop from start to end twice and omit same indices.
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]);
}
}
回答2:
What you want is... mathematically... not permutations, but variations without repetition (but that's actually irrelevant).
I wrote a code for this in PHP a bit earlier, here's its JS variant (selects a given number of elements, can handle repetitions in data, etc.):
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(' ')))
回答3:
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (i === j) continue;
console.log(arr[i] + ' ' + arr[j]);
}
}
来源:https://stackoverflow.com/questions/62436810/how-to-make-permutation-in-javascript