What is the difference between these two chunks of code?

Viewed 72

Can someone please help me understand the differences between these two programs? I was doing this RallyCoding Prep problem and wrote the first program (and it failed). Then I checked what others did to try and understand but it seems to me that the two programs do basically the same thing, written differently. Can someone help me understand why mine fails and the second program works?

Link to problem: https://www.rallycoding.com/problems/205

--My code--

            
let k = 16;

let length = Math.sqrt(k);
let height = length;

let arr = []
for(let i = 0; i < length; i++){
  let row = [];
  for(let x = 1; x <= k; x++){
    row.push(x);
  }

  arr.push(row);
}

console.log(arr)

--Their code--

let k = 16  
let c = 1;
const r = Math.sqrt(k);
const result = [];
while(c <= k) {
  const block = [];
  for (let i = 1; i <= r; i++) {
    block.push(c);
    c++;
  }
  result.push(block);
}

console.log(result)

I'm certain I'm missing something very obvious. I hope someone can help me understand this. Thank you!

3 Answers

You code produces data like this: [[1, 2, 3], [1, 2, 3], ...]

(Each sub-array starts with 1)

You need to produce: [[1, 2, 3], [4, 5, 6], ...]

(Each sub array continues the sequence of the previous one)

the nested forloop you created loop over 16 times for(let x = 1; x <= k; x++){ row.push(x); } because K=16 so it will provide an array with 16 element. the forloop keep runing intel it finish the job.but in the correction they use a "while" loop because The 'while' loop used only when the number of iteration are not exactly known.the are some diff between the two. Here's a link you can find more

Since the value of k = 16, the inner loop runs 16 times. So, the result produced by your code is

[
   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
]

And the result produced by their code is

[
   [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12],
   [13, 14, 15, 16]
]

So, you can make these changes in your code to get the desired result.

let k = 16;

let length = Math.sqrt(k);
let height = length;

let arr = []
for(let i = 0; i < length; i++){
   let row = [];
   for(let x = 1; x <= length; x++){
      row.push(x + i * length);
   }
   arr.push(row);
}
Related