views:

41

answers:

2

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

A: 
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
SHiNKiROU
A: 

[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

galambalazs