The author says: The array stores its content in a single array of width × height elements. The elements are stored row by row, so, for example, the third element in the fifth row is (using zero-based indexing) stored at position 4 × width + 2. the problem is how it is possible to have a coherent array if say the width is 5 when the index will never reach no 2 because of the equation in the square brackets;

   let content = [];
   function element(x,y){return undefined;}

for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    content[y * width + x] = element(x, y);
  }
}

1 Answers

1
Kostyuk Rostyslav On Best Solutions

Hi I am not sure I understood correctly your question but I try to explain to you the code you have wrote.

As you have wroten, the code represents 2D matrix as one dimensional array. So if we want to create a 3 x 2 matrix, which would look like this (logicaly)

undefinded0, undefinded1
undefinded2, undefinded3
undefinded4, undefinded5

(i put a number to make think easier) if we use your function the representation would look like this

[undefined0, undefined1, undefined2, undefined3, undefined4, undefined5] 

the problem is how it is possible to have a coherent array if say the width is 5 when the index will never reach no 2 because of the equation in the square brackets

Yep thats true, the array has only one dimension, which means there will be only one element that stays at index 2. I think you may have confuse the one line representation with some sort bidimensional representation. Here let me do an example. If you have the matrix like this

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

Each row (even the fifth row) will have an element with index 2, this is the representation above has two dimensions.