开发者

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

开发者 https://www.devze.com 2023-01-20 02:33 出处:网络
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, s

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  
OOO开发者_如何学PythonOO  
XOOOX  
XXOXX  


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.


[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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消