保留每个项目的索引位置的数组的笛卡尔积

时间:2019-10-20 11:10:58

标签: javascript

我正在寻找笛卡尔积,但是我需要每个项目都保留其索引。

例如,这是笛卡尔积:

function cartesian() {
    var r = [], arg = arguments, max = arg.length-1;
    function helper(arr, i) {
        for (var j=0, l=arg[i].length; j<l; j++) {
            var a = arr.slice(0); // clone arr
            a.push(arg[i][j]);
            if (i==max)
                r.push(a);
            else
                helper(a, i+1);
        }
    }
    helper([], 0);
    return r;
}
cartesian([1,2,3],[11,22,33],[111,222,333])

它返回此:

[ [ 1, 11, 111 ],
  [ 1, 11, 222 ],
  [ 1, 11, 333 ],
  [ 1, 22, 111 ],
  [ 1, 22, 222 ],
  [ 1, 22, 333 ],
  [ 1, 33, 111 ],
  [ 1, 33, 222 ],
  [ 1, 33, 333 ],
  [ 2, 11, 111 ],
  [ 2, 11, 222 ],
  [ 2, 11, 333 ],
  [ 2, 22, 111 ],
  [ 2, 22, 222 ],
  [ 2, 22, 333 ],
  [ 2, 33, 111 ],
  [ 2, 33, 222 ],
  [ 2, 33, 333 ],
  [ 3, 11, 111 ],
  [ 3, 11, 222 ],
  [ 3, 11, 333 ],
  [ 3, 22, 111 ],
  [ 3, 22, 222 ],
  [ 3, 22, 333 ],
  [ 3, 33, 111 ],
  [ 3, 33, 222 ],
  [ 3, 33, 333 ] ]

但是我需要它来返回它:

[
  [1, 2, 3],
  [1, 2, 33],
  [1, 2, 333],
  [1, 22, 3],
  [1, 22, 33],
  [1, 22, 333],
  [1, 222, 3],
  [1, 222, 33],
  [1, 222, 333],
  [11, 2, 3],
  [11, 2, 33],
  [11, 2, 333],
  [11, 22, 3],
  [11, 22, 33],
  [11, 22, 333],
  [11, 222, 3],
  [11, 222, 33],
  [11, 222, 333],
  [111, 2, 3],
  [111, 2, 33],
  [111, 2, 333],
  [111, 22, 3],
  [111, 22, 33],
  [111, 22, 333],
  [111, 222, 3],
  [111, 222, 33],
  [111, 222, 333]
]

数组的数组可以不排序,但是数字数组应保留其索引(在这种情况下,它们是排序的,但并非总是如此)。另外,如果此算法的名称不是笛卡尔,那么我也会有兴趣知道。

0 个答案:

没有答案