如何将两个数组组合成笛卡尔积?

6

我有

array1 = [1,2,3,4,5];
array2 = ["one","two","three","four","five"];

我希望得到array3,其中包含所有与array2的第一个(和其他)元素相匹配的array1元素等等。

例如:

array3 = ["one 1", "two 1", "three 1", "four 1", "five 1", "one 2", "two 2", "three 2", "four 2", "five 2"...]

我知道需要使用for循环,但不知道如何操作。


1
如果你使用的是underscore或lodash,一个简单的zipWith就可以解决问题:_.zipWith(array1, array2, function(a,b) { return a + ' ' + b; }); - BlueRaja - Danny Pflughoeft
7个回答

12

您可以使用Array.prototype.forEach()来迭代数组。

forEach() 方法针对数组中的每个元素执行一次提供的函数。

var array1 = [1, 2, 3, 4, 5],
    array2 = ["one", "two", "three", "four", "five"],
    result = [];

array1.forEach(function (a) {
    array2.forEach(function (b) {
        result.push(b + ' ' + a);
    });
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');


11

您可以使用两个for循环:

var array1 = [1,2,3,4,5];
var array2 = ["one","two","three","four","five"];

var array3 = [];
for (var i = 0; i < array1.length; i++) {
    for (var j = 0; j < array2.length; j++) {
        array3.push(array2[j] + ' ' + array1[i]);
    }
}

console.log(array3);

6

使用 reducemapconcat 的另一种方法。

Snippet based on @Nina Scholz

var array1 = [1, 2, 3, 4, 5],
    array2 = ["one", "two", "three", "four", "five"];

var result = array1.reduce(function (acc, cur) {
    return acc.concat(array2.map(function (name) {
        return name + ' ' + cur;
    }));
},[]);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');


5

仍有使用循环的选项:

var array2 = [1,2,3,4,5],
array1 = ["one","two","three","four","five"],
m = [];
for(var a1 in array1){  
  for(var a2 in array2){
      m.push( array1[a1]+ array2[a2] );    
  }
}
console.log(m);

4
请勿使用 for...in 循环来遍历数组,如果索引顺序很重要的话。注意:这句话是关于 JavaScript 的内容,来源于 MDN。 - Grundy

3

You can use this method when array1.length and array2.length are equal.

var array1 = [1, 2, 3, 4, 5];
var array2 = ["one", "two", "three", "four", "five"];
var length = array1.length;
var array3 = new Array(Math.pow(length, 2)).fill(0).map((v, i) => array2[i % length] + ' ' + array1[i / length << 0]);


document.body.textContent = JSON.stringify(array3);


如果数组长度不同怎么办? - Grundy
1
@Grundy 这个问题没有提到它。 - Lewis
是的,但我认为你应该添加细节说明这适用于长度相同的数组。 - Grundy

0

尝试(JS)

function myFunction(){
            var F = [1, 2, 3, 4,5];
            var S = ["one", "two", "three", "four", "five"];
            var Result = [];

           var k=0;
            for (var i = 0; i < F.length; i++) {
                for (var j = 0; j < S.length; j++) {
                    Result[k++] = S[j] + " " + F[i];
                }
            }

            console.log(Result);
        }

1
这是一个JS问题。原帖的作者可能能够从中推断出代码,但我认为这并没有什么用处。 - Andy
Corrected it please check - Abdul Razak

0

由于这不是语言内置的功能,因此这里提供一个具有类似签名的简单函数,类似于内置的zip

func cartesianProduct<Sequence1, Sequence2>(_ sequence1: Sequence1, _ sequence2: Sequence2) -> [(Sequence1.Element, Sequence2.Element)]
    where Sequence1 : Sequence, Sequence2 : Sequence
{
    var result: [(Sequence1.Element, Sequence2.Element)] = .init()
    sequence1.forEach { value1 in
        sequence2.forEach { value2 in
            result.append((value1, value2))
        }
    }
    return result
}

print(Array(zip([1, 2, 3], ["a", "b"]))) // [(1, "a"), (2, "b")]
print(cartesianProduct([1, 2, 3], ["a", "b"])) // [(1, "a"), (1, "b"), (2, "a"), (2, "b"), (3, "a"), (3, "b")]

在您的情况下,您可以这样做:

cartesianProduct([1,2,3,4,5], ["one","two","three","four","five"])
  .map { "\($0.1) \($0.0)" }

或者甚至:

cartesianProduct(1...5, ["one","two","three","four","five"])
  .map { "\($0.1) \($0.0)" }

这两个都会生成序列:

["one 1", "two 1", "three 1", "four 1", "five 1", "one 2", "two 2", "three 2", "four 2", "five 2", ...]

由于在集合的元素上执行此操作很常见,因此我还创建了这两个函数扩展:

extension Collection {
    /// O(n^2)
    func pairElementToEveryOtherElement() -> [(Self.Element, Self.Element)] {
        var result = [(Self.Element, Self.Element)]()
        for i in indices {
            var j = index(after: i)
            while j != endIndex {
                result.append((self[i], self[j]))
                j = index(after: j)
            }
        }
        return result
    }

    /// O(n)
    public func pairElementToNeighbors() -> [(Self.Element, Self.Element)] {
        if isEmpty {
            return .init()
        }

        var result: [(Self.Element, Self.Element)] = .init()
        var i = startIndex
        while index(after: i) != endIndex {
            result.append((self[i], self[index(after: i)]))
            i = index(after: i)
        }
        return result
    }
}

可以按照以下方式使用:

let inefficientHasDuplicatesCheck = myCollection
  .pairElementToEveryOtherElement()
  .contains { $0.0 == $0.1 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接