[英]Reverse of a cartesian product
Given the code below: 给出以下代码:
function cartesianProductOf() {
return _.reduce(arguments, function(a, b) {
return _.flatten(_.map(a, function(x) {
return _.map(b, function(y) {
return x.concat([y]);
});
}), true);
}, [ [] ]);
};
var cp = cartesianProductOf([1, 2], [3, 4], ['a', 'b']); // [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]]
I am looking for a way to reverse the process, such that 我正在寻找一种逆转这一过程的方法,例如
reverseCartesian(cp,[3,4]); // [[1,'a'],[1,'b'],[2,'a'],[2,'b']]
I don't think this would perform faster with real data, but you can do it like this 我认为使用实际数据执行此操作不会更快,但是您可以这样做
function reverseCartesian(cp, arr) {
return _.chain(cp)
.map(_.partial(_.difference, _, arr))
.uniq(function(currentItem) {
return currentItem.join("|");
})
.value();
}
console.log(reverseCartesian(cp, [3, 4]));
// [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ]
Note: This will not work properly if the arrays have elements with |
注意:如果数组中的元素带有
|
则将无法正常工作|
in them. 在他们中。 Choose this character (or set of characters) carefully in such a way that they will not occur in the arrays.
仔细选择此字符(或一组字符),以免它们出现在数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.