Ad

How To Fill Numbers In Triangle Multidimensional Arrays?

how to fill numbers in these arrays?

[ 
 [ 0 ], 
 [ 0, 0 ], 
 [ 0, 0, 0 ], 
 [ 0, 0, 0, 0 ] 
]

what i got for nested loops, the numbers i fill is same like the numbers of target(num) ; it repeats numbers target(num) in those arrays

looks below:

var arr = [
  [0],
  [0, 0],
  [0, 0, 0],
  [0, 0, 0, 0]
]
var num = 20

for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr[i].length; j++) {
    for (var k = 0; k <= num; k++) {
      arr[i][j] = k
    }
  }
};
console.log(arr)

the output i want is like this :

[ 
 [ 1 ], 
 [ 3, 5 ], 
 [ 7, 9, 11 ], 
 [ 13, 15, 17, 19 ] 
]

can anyone explain why my codes repeat the same number ? unlike the output i want

Ad

Answer

In the innermost loop, you're reassigning arr[i][j] = k over and over again, until k reaches 20. So, every time the innermost loop is reached, arr[i][j] becomes 20.

You only need 2 loops: an outer (loop over arr) and an inner one (loop over each subarray), while keeping a persistent counter outside:

var arr = [
  [0],
  [0, 0],
  [0, 0, 0],
  [0, 0, 0, 0]
];

var counter = 1;
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr[i].length; j++) {
    arr[i][j] = counter;
    counter++;
  }
}
console.log(arr);

(also note that a for loop's } should not have a ; after it)

To display only odd numbers:

var arr = [
  [0],
  [0, 0],
  [0, 0, 0],
  [0, 0, 0, 0]
];

var counter = 1;
for (var i = 0; i < arr.length; i++) {
  for (var j = 0; j < arr[i].length; j++) {
    arr[i][j] = counter;
    counter += 2;
  }
}
console.log(arr);

Ad
source: stackoverflow.com
Ad