Home > OS >  Fill diagonals of array with same values in JS
Fill diagonals of array with same values in JS

Time:03-12

Given n and values array (values.length = 2 * n - 1), I want to fill an array of n x n elements, in a way that its diagonals will have the same values as follows:

ex. n = 3, values = [0, 1, 2, 3, 4]:

0 1 2
3 0 1
4 3 0

arr = [0, 1, 2, 3, 0, 1, 4, 3, 0]

ex. n = 4, values = [0, 1, 2, 3, 4, 5, 6];

0 1 2 3
4 0 1 2
5 4 0 1
6 5 4 0

arr = [0, 1, 2, 3, 4, 0, 1, 2, 5, 4, 0, 1, 6, 5, 4, 0]

I was able to fill upper half of the array using the following code, but got stuck with the rest:

var n = 3;
var values = [0, 1, 2, 3, 4]

var a = [];
for (var i = 0; i < n; i  ) {
    for (var j = 0; j < n; j  ) {
        a[j * n   i] = values[i - j];
    }
}

/* Result
0 1 2
  0 1
    0

arr = [0, 1, 2, undefined, 0, 1, undefined, undefined, 0]

Expected output:
0 1 2
3 0 1
4 3 0

arr = [0, 1, 2, 3, 0, 1, 4, 3, 0] */

Length of values array is 2 * n - 1, which is the count of diagonals of the array.

Any ideas how to fill the whole array?

CodePudding user response:

Created while loop and added counter. Counter counts the elements suppose to be cut from end. first loop goes thru these elements and adds them to the beginning, second loop limited by this counter so it doesnt hit the end of the array and it adds the elemets havent been cutted from the array to the end. until all elements are cut from the array.

var values = [0, 1, 2, 3, 4]

var a = [];
var ctr = 0
while(ctr < values.length){
  for(let i = (values.length - ctr); i < values.length; i  ){
    a.push(values[i]);
  }
  
  for(let i = 0; i < (values.length - ctr); i  ){
    a.push(values[i]);
  }
  ctr  ;
}

Output

[0, 1, 2, 3, 4, 4, 0, 1, 2, 3, 3, 4, 0, 1, 2, 2, 3, 4, 0, 1, 1, 2, 3, 4, 0]

0 1 2 3 4
4 0 1 2 3
3 4 0 1 2
2 3 4 0 1
1 2 3 4 0

CodePudding user response:

Ok, I saw the requested results and made this snippet below I use a two dimensional array to be able to check if there is an existing diagonal using x y logic and if there was not, there was a counter that would reference the next array number(c 1%arr.length)

EDIT EXPLAINED: I saw what was going on then I decided to try only adding when there was no diagonal in that "place".. it works like a charm

  • Related