Zum Dummi
Zum Dummi

Reputation: 233

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

Upvotes: 0

Views: 93

Answers (3)

CertainPerformance
CertainPerformance

Reputation: 370689

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);

Upvotes: 1

Mukesh Fulwariya
Mukesh Fulwariya

Reputation: 46

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 third for loop always executing code 20 times.Therefor every index of array store the last looping value i.e 20

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can do it with a variable to keep track of value to be inserted and map

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

let value = 0;

let op= arr.map(e=>{
  return e.map(el=> el=++value)
})
console.log(op)

Upvotes: 0

Related Questions