LiamG_G LiamG_G - 3 years ago 146
Javascript Question

Check nearby point in 2d array with boundary conditions

I have a program that checks a coordinate in an array of arrays, and searches nearby coordinates to find the nearest 5 with an 'event'. However, when at the edges of the grid, in this example (0,0), I face the problem of the same event being returned multiple times but with a different 'distance' away (this distance is the Manhattan distance).

I think this occurs because I have parameters set the that if the coordinate it wants to check is outside of the grid (less than 0) it's value is changed to match the boundary (0).

let check = (x, y, d) => {
if (x > 20) {
x = 20;
}
if (x < 0) {
x = 0;
}
if (y > 20) {
y = 20;
}
if (y < 0) {
y = 0;
}

if (Main[x][y].event) {
let info = {
x: x - (xRange/2),
y: y - (xRange/2),
event: Main[x][y].event,
distance: d,
ticket: Main[x][y].tickets[0],
}
return info;
} else {
return false;
}
}

let findEvents = (x, y) => {
let nearby = [];
let info;

// Check point x, y
if (Main[x][y].event) {
info = {
x: x - (xRange/2),
y: y - (xRange/2),
event: Main[x][y].event,
distance: 0,
tickets: Main[x][y].tickets,
}
nearby.push(info);
}

for (let d = 1; d <= 40; d++) {
for (let i = 0; i < d + 1; i++) {

info = check(x - d + i, y - i, d);

if (info) {
nearby.push(info);
}
if ((nearby.length > 5) &&
(nearby[(nearby.length-1)].distance !=
nearby[(nearby.length-2)].distance)) {
return nearby.slice(0,-1);
}

info = check(x + d - i, y + i, d);

if (info) {
nearby.push(info);
}
if ((nearby.length > 5) &&
(nearby[(nearby.length-1)].distance !=
nearby[(nearby.length-2)].distance)) {
return nearby.slice(0,-1);
}
}

for (let i = 1; i < d; i++) {

info = check(x - i, y + d - i, d);

if (info) {
nearby.push(info);
}
if ((nearby.length > 5) &&
(nearby[(nearby.length-1)].distance !=
nearby[(nearby.length-2)].distance)) {
return nearby.slice(0,-1);
}

info = check(x + d - i, y - i, d);

if (info) {
nearby.push(info);
}
if ((nearby.length > 5) &&
(nearby[(nearby.length-1)].distance !=
nearby[(nearby.length-2)].distance)) {
return nearby.slice(0,-1);
}
}
}
return nearby;
}


Any tips on how to avoid this? (or to clean up my code in general :D )

Answer Source

I don't fully understand your find_events method yet, but it seems like to avoid the problem you described, you should return false from check whenever the point is outside the grid. Thus:

let check = (x, y, d) => {
  if (x > 20 || x < 0 || y > 20 ||y < 0) {
    return false;
  }
...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download