JS:给定一个x,y坐标列表,找到1,1和最大给定之间的缺失坐标

时间:2013-12-16 18:10:52

标签: javascript arrays math coordinates

说我有:

var coords = [
    [2, 2],
    [2, 4],
    [3, 2],
    [3, 4]
];

var missing = [];

使用vanilla javascript,我如何检查coords每个缺失的x,y值,从[1, 1]开始,结束于比coords中的最大值1更多({ {1}})。

我有一个jsFiddle,我到目前为止所得到的但是我只能找回[4, 5]的值:http://jsfiddle.net/UWE5x/我可以看到为什么我不知道从哪里去这里。

我确信这比我目前的路线更有效。

2 个答案:

答案 0 :(得分:0)

以下内容应该有效:

var coords = [
    [2, 2],
    [2, 4],
    [3, 2],
    [3, 4]
];

var max_x = -1, max_y = -1, x, y;
var missing = [];
coords_obj = {};
for (var i = 0; i < coords.length; i++) {
    x = coords[i][0];
    y = coords[i][1];
    if (x > max_x) max_x = x;
    if (y > max_y) max_y = y;
    if (!coords_obj[x])
        coords_obj[x] = {};
    coords_obj[x][y] = 1;
}

for (x = 1; x <= max_x + 1; x++) {
    for (y = 1; y <= max_y + 1; y++) {
        if (!coords_obj[x] || !coords_obj[x][y])
            missing.push([x, y]);
    }
}

这导致missing

的以下内容
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,3],[2,5],[3,1],[3,3],[3,5],[4,1],[4,2],[4,3],[4,4],[4,5]]

答案 1 :(得分:0)

使用 Ramda functional programming library ,我们可以相当简单地执行此操作,如 JSFiddle 所示:

var missing = reject((function() {
    var makeKey = function(pair) {return pair[0] + "," + pair[1];};
    var found = map(makeKey, coords);
    return function(pair) {
        return contains(makeKey(pair), found);
    };
})(), xprod(
    range(1, 2 + Math.max.apply(null, map(get('0'), coords))),
    range(1, 2 + Math.max.apply(null, map(get('1'), coords)))
));

Ramda仍处于开发阶段。如果它的difference运算符类似于union运算符,那么这将更简单。像 Underscore 这样的库可以使用类似的工具来简化(包括difference。)


更新

我对这个解决方案感到不满意,并且从 Ramda 中显示的内容不足,所以我对该库进行了一些补充,我认为这样可以实现 nicer code 现在:

var pairEq = andFn(eqProps(0), eqProps(1));

var missing = differenceWith(pairEq, xprod(
    range(1, 2 + max(map(get('0'), coords))),
    range(1, 2 + max(map(get('1'), coords)))
), coords);

我知道这可能对OP来说并不重要,但它明确了对我知道我想要的几个功能的需求,但是我还没有考虑到这个功能,但是我还没有考虑过这个功能(虽然我最终没有在最终版本中使用那个。)

Ramda现在有maxminmaxWithminWitheqPropintersectionintersectionWith,{{ 1}},differencedifferenceWithallPredicates个函数。此解决方案利用anyPredicatesmaxeqProp,但使用现有的differenceWith代替andFn。令人惊讶的是,一个小小问题可以带来多少变化!

相关问题