2017-07-25 62 views
1

我有一個程序檢查數組數組中的座標,並搜索附近的座標以找到與「事件」最近的5個座標。然而,在網格的邊緣,在這個例子中(0,0),我面臨同一個事件被多次返回但距離不同的距離(這個距離是曼哈頓距離)的問題。用邊界條件檢查二維數組中的附近點

我認爲這是因爲我有參數設置,如果它想檢查的座標是在網格之外(小於0)它的值被改變以匹配邊界(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; 
    } 

有關如何避免這種情況的任何提示? (或清理我的代碼一般:D)

回答

1

我還沒有完全理解你的find_events方法,但它似乎要避免你描述的問題,你應該返回false從check只要點在外面格。因此:

let check = (x, y, d) => { 
    if (x > 20 || x < 0 || y > 20 ||y < 0) { 
    return false; 
    } 
... 
+0

是的工作:D我有點太集中在值超出範圍,似乎忽略它仍然會嘗試其他值在相同的距離。 我基於我的方法在https://stackoverflow.com/questions/3330181/algorithm-for-finding-nearest-object-on-2d-grid如果你想嘗試和更好地理解:)謝謝 –