简体   繁体   English

计算1数组中元素的笛卡尔积

[英]Compute cartesian product of elements in 1 array

I want to compute the cartesian product inside the single elements of an array. 我想在数组的单个元素内计算笛卡尔乘积。 There should only be 2 values at a time. 一次只能有2个值。
So if this my array is: 因此,如果我的数组是:

[["cat dog mouse"], ["blue red green"]]

The expected value is: 预期值为:

  • cat, dog 猫狗
  • cat, mouse 猫,老鼠
  • dog, mouse 狗,老鼠
  • blue, red 蓝红
  • blue, green 蓝绿
  • red, green 红色,绿色

This is my buggy approach: 这是我的越野车方法:

var arr = [["cat dog mouse"], ["blue red green"], ["apple orange banana"]];

for (i = 0; i < arr.length; i++) {
    for(j = 0; j < arr[i].length; j++){
        if(j >= arr[i].length){
            console.log(arr[i][j].split( " ")  + " "  + arr[i][0])
        }else{
            console.log(arr[i][j].split( " ")  + " "  + arr[i][j+1])
        }
    }
}

It gives me 它给了我

  • cat,dog,mouse undefined 猫,狗,老鼠未定义
  • blue,red,green undefined 蓝色,红色,绿色未定义

You can do something like this using split() and for loop 您可以使用split()for循环执行类似的操作

 var arr = [ ["cat dog mouse"], ["blue red green"], ["apple orange banana"] ]; // iterate the array for (i = 0; i < arr.length; i++) { // split the string var inArr = arr[i][0].split(' '); // iterate the splitted string array for (j = 0; j < inArr.length - 1; j++) { // iterate string next to current string for (k = j + 1; k < inArr.length; k++) // generate the output console.log(inArr[j] + ', ' + inArr[k]); } } 

You were close, some modified code 您接近了,修改了一些代码

var arr = [["cat dog mouse"], ["blue red green"], ["apple orange banana"]];

for (i = 0; i < arr.length; i++) {
    var items = arr[i][0].split(" ")
    for (j = 0; j < items.length - 1; j++) {
        for (k = j+1; k < items.length; k++) {
            console.log(items[j], items[k])
        }
    }
}

result: 结果:

cat dog
cat mouse
dog mouse
blue red
blue green
red green
apple orange
apple banana
orange banana
[["cat dog mouse"], ["blue red green"]].forEach(function (item) {
    item.forEach(function (value) {
         var arr = value.split(' ');
         var hash = {};
         arr.forEach(function (firstItem) {
              arr.forEach(function (secondItem) {
                  if (firstItem !== secondItem && !hash[firstItem + secondItem] && !hash[secondItem + firstItem]) {
                      console.log(firstItem + ', ' + secondItem);
                      hash[firstItem+secondItem] = true;
                  }
              });
         })
    });
});

A solution splited in partial solutions, one for the arrays and one for the combination without repeat. 一种解决方案分为部分解决方案,一个用于数组,一个用于组合,无需重复。

 function combine(array, length) { function c(l, r) { var ll = l.slice(); if (r.length === length) { result.push(r); return; } while (ll.length) { c(ll, r.concat(ll.shift())); } } var result = []; c(array, []); return result; } function get(array) { return array.map(function (a) { return combine(a[0].split(' '), 2); }); } var result = get([["cat dog mouse"], ["blue red green"], ["apple orange banana"]]); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

You can do it in functional way , just using .map() and .forEach() method : 您可以使用.map().forEach()方法以功能方式进行操作:

var arr = [["cat dog mouse"], ["blue red green"], ["apple orange banana"]];


function print(item){
  //If there is one last item we stop the process
  if (item.length <= 1) return;
  else {
    //Retrieve head of our stack and shift the first item
    const head = item.shift();
    item.forEach((elm) => console.log(head + ',' + elm));
    // call our recursive function with the new array
    return print(item);
  }
}

function combine(arr){
  //Return array splited by using .map and .split operations, then iterate by using forEach and call our
  // recursive function
  arr
    .map((array) => array[0].split(' '))
    .forEach((value) => print(value));
}

combine(arr);

You can check the Plunker 您可以检查柱塞

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM