H
H
hardWell2017-09-03 11:19:04
JavaScript
hardWell, 2017-09-03 11:19:04

Filling an array in Javascript?

Hello ! tell me how to fill the array as shown in the image here is my code
cba62ce2aeaf492c8f543ed135ab5155.jpg

var arr = [];
var rows = 7;
var cols = 7;
for (var i = 0; i < rows; i++) {
    arr[i] = [];
  for (var j = 0; j < cols; j++) {
    arr[i][j] = i;
    if (i == j || i == cols-j-1) {
      arr[i][j] = 1;
    } else {
      arr[i][j] = 0;
    }
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2017-09-03
@hardWell

function getArr(size) {
  const arr = [...Array(size)].map(() => Array(size).fill(0));

  // если размер чётный, непонятно, где выставлять единицы, так что выставляем только для нечётных
  if (size & 1) {
    const middle = (size / 2) | 0;
    arr.forEach((n, i) => n[i] = arr[middle][i] = n[middle] = n[size - i - 1] = 1);
  }

  return arr;
}

You can evaluate the result of the work as follows, for example:
It will output something like this:
100000000010000000001
010000000010000000010
001000000010000000100
000100000010000001000
000010000010000010000
000001000010000100000
000000100010001000000
000000010010010000000
000000001010100000000
000000000111000000000
111111111111111111111
000000000111000000000
000000001010100000000
000000010010010000000
000000100010001000000
000001000010000100000
000010000010000010000
000100000010000001000
001000000010000000100
010000000010000000010
100000000010000000001

A
Artyom Egorov, 2017-09-03
@egoroof

You are welcome!

var a = [
  [1, 0, 0, 1, 0, 0, 1],
  [0, 1, 0, 1, 0, 1, 0],
  [0, 0, 1, 1, 1, 0, 0],
  [1, 1, 1, 1, 1, 1, 1],
  [0, 0, 1, 1, 1, 0, 0],
  [0, 1, 0, 1, 0, 1, 0],
  [1, 0, 0, 1, 0, 0, 1]
];

S
Sergey Sokolov, 2017-09-03
@sergiks

You can simply go through everything in turn and check the fulfillment of one of the conditions:
belonging to the diagonal, position exactly in the middle of the X or Y axis:

function makeStar(side) {
  var arr = new Array(side), x, y, mid = (side-1)/2;
  for( y = 0; y < side; y++) {
    row = arr[y] = new Array(side);
    for( x = 0; x < side; x++) {
      row[x] = (y===x || x===side-1-y || x===mid || y===mid) ? 1 : 0;
    }
  }
  return arr;
}

makeStar(4)
  .reduce((p,c)=>{ return p + c.join(',') + "\n"},'')

/*
1,0,0,1
0,1,1,0
0,1,1,0
1,0,0,1
*/

Surely, there are very beautiful solutions to the same problem (I did not look for it). You can use similarity - the upper left quarter is equal to the lower right. You can beat the rotation around the center.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question