Javascript - 在单个数组中生成所有元素组合(成对) [英] Javascript - Generating all combinations of elements in a single array (in pairs)
问题描述
我已经看到了几个关于如何生成数组中元素的所有可能组合的类似问题.但是我很难弄清楚如何编写一个只输出组合对的算法.任何建议将不胜感激!
I've seen several similar questions about how to generate all possible combinations of elements in an array. But I'm having a very hard time figuring out how to write an algorithm that will only output combination pairs. Any suggestions would be super appreciated!
从以下数组开始(有 N 个元素):
Starting with the following array (with N elements):
var array = ["apple", "banana", "lemon", "mango"];
并得到以下结果:
var result = [
"apple banana"
"apple lemon"
"apple mango"
"banana lemon"
"banana mango"
"lemon mango"
];
我正在尝试以下方法,但这会产生所有可能的组合,而只是组合对.
I was trying out the following approach but this results in all possible combinations, instead only combination pairs.
var letters = splSentences;
var combi = [];
var temp= "";
var letLen = Math.pow(2, letters.length);
for (var i = 0; i < letLen ; i++){
temp= "";
for (var j=0;j<letters.length;j++) {
if ((i & Math.pow(2,j))){
temp += letters[j]+ " "
}
}
if (temp !== "") {
combi.push(temp);
}
}
推荐答案
一个简单的方法是对数组执行双循环,在第二个循环中跳过第一个 i
元素.
A simple way would be to do a double for loop over the array where you skip the first i
elements in the second loop.
let array = ["apple", "banana", "lemon", "mango"];
let results = [];
// Since you only want pairs, there's no reason
// to iterate over the last element directly
for (let i = 0; i < array.length - 1; i++) {
// This is where you'll capture that last value
for (let j = i + 1; j < array.length; j++) {
results.push(`${array[i]} ${array[j]}`);
}
}
console.log(results);
用 ES5 重写:
var array = ["apple", "banana", "lemon", "mango"];
var results = [];
// Since you only want pairs, there's no reason
// to iterate over the last element directly
for (var i = 0; i < array.length - 1; i++) {
// This is where you'll capture that last value
for (var j = i + 1; j < array.length; j++) {
results.push(array[i] + ' ' + array[j]);
}
}
console.log(results);
这篇关于Javascript - 在单个数组中生成所有元素组合(成对)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!