JS: how to algorithmically highlight a diamond-shaped selection of x/y coordinates?

谁说胖子不能爱 提交于 2019-12-23 02:01:59

问题


If given an array of arrays creating an n x n map of tiles, is there a way to loop through an algorithm that would highlight tiles which form a diamond shape? (the key problem is not to hardcode it, so it could work for any sized map)

For example: if the map was 5x5 tiles like so:

XXXXX  
XXXXX  
XXXXX  
XXXXX  
XXXXX  

How could an algorithm highlight a diamond shape like so:

XXOXX  
XOOOX  
OOOOO  
XOOOX  
XXOXX  

回答1:


[Working example]

function diamond(arr) {
  var len = arr.length;
  var mid = Math.floor(len / 2);
  for (var i = 0; i < len; i++) {
    var d = Math.abs(i - mid);
    for (var j = d; j < len - d; j++) {
      arr[i][j] = arr[i][j] = 1;
    }
  }
  return arr;
}

Please note that you haven't defined the expected behavior for even numbers




回答2:


I know this is an old topic but I think I just figured out the best method.

If cX,cY is the center of the diamond and r is the "radius" (not the diameter) use this condition in your loop:

if (Math.abs(x-cX)+Math.abs(y-cY)<r)
    arr[x][y] = 1;      

so cX=2, cY=2, r=3 would draw

0,0,1,0,0
0,1,1,1,0
1,1,1,1,1
0,1,1,1,0
0,0,1,0,0

Now you can set cX and cY to your mouse position and increase/descrease the diamond size using r.




回答3:


function diamond(arr) {

var m = Math.floor(arr.length / 2); // mid
var i = 0;
for (; i < arr.length / 2; i ++) {
  for (var j = 0; j <= i; j ++) {
    for (var k = 0; k <= j; k ++) {
      arr[i][m + k] = arr[i][m - k] = 1;
    }
  }
}

for (; i < arr.length; i ++) {
  for (var j = arr.length - 1 - i; j >= 0; j --) {
    for (var k = 0; k <= j; k ++) {
      arr[i][m + k] = arr[i][m - k] = 1;
    }
  }
}

return arr;

}

>> Example: (9x9 array)

diamond((function(n) { var a = []; for (var i = 0; i < n; i ++) { a[i] = []; for (var j = 0; j < n; j ++) { a[i][j] = 0; } }; return a;})(9)).join('\n');

=> Output:

0,0,0,0,1,0,0,0,0
0,0,0,1,1,1,0,0,0
0,0,1,1,1,1,1,0,0
0,1,1,1,1,1,1,1,0
1,1,1,1,1,1,1,1,1
0,1,1,1,1,1,1,1,0
0,0,1,1,1,1,1,0,0
0,0,0,1,1,1,0,0,0
0,0,0,0,1,0,0,0,0


来源:https://stackoverflow.com/questions/3952142/js-how-to-algorithmically-highlight-a-diamond-shaped-selection-of-x-y-coordinat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!