# Could I rewrite this function with single loop?

I have a suspicion that function like below can be written with single loop(maybe not), but can’t figure out, how to achieve that.

``````//TASK function must return 2-dimensional array,
//representing NxN grid(matrix), with coordinates(indexes) for each element

//WHY? some visualization seems to be helpful when working on
//Project Euler 11 problem

const generateQuadraticTestGrid = (size) => {

let testGrid = [];

for (let i = 0; i < size; i++) {
testGrid.push([])
for (let j = 0; j < size; j++) {
testGrid[i].push(String(i) + ',' + String(j));
}

}

return testGrid;

}

/*
Output:

[
[ '0,0', '0,1', '0,2', '0,3', '0,4', '0,5' ],
[ '1,0', '1,1', '1,2', '1,3', '1,4', '1,5' ],
[ '2,0', '2,1', '2,2', '2,3', '2,4', '2,5' ],
[ '3,0', '3,1', '3,2', '3,3', '3,4', '3,5' ],
[ '4,0', '4,1', '4,2', '4,3', '4,4', '4,5' ],
[ '5,0', '5,1', '5,2', '5,3', '5,4', '5,5' ]
]
*/
``````

Can you elaborate a little more on your suspicions? Don’t worry so much about creating a multi-dimensional array right now. How would you dynamically create a single array and add `n` elements to it without using some form of iteration?

2 Likes

That’s a question I needed to hear I guess.

There was discussion about some problem related to 2-dimensional arrays. At some point it became clear, that there single loop could be used instead of nested loops.

I guess I am just overthinking stuff after that, making bad analogies. My problem here is to generate array, not to access elements in existing array.

I don’t think you are using the word ‘quadratic’ correctly here.

Using `push` is a particularly slow way to build up an array in Javascript, if you are making a big array.

Yeah, that’s the case probably. What would be appropriate word in English?

If you are making a 2D array, I’d just call it a 2D array.

Well, if 2D array has size NxN(4x4 for example), and it is filled with numbers:

it’s basically matrix,right? If matrix has NxN size, how do I call it? square maybe?
quadratic it was just similar to my native language word for such thing

It’s just a 2D array in programming. You could call it a square matrix fr math applications, but it certainly is not quadratic. ‘Quadratic’ has a specific mathematical meaning.

Thanks, I think terminology became clear for me.
I am reading this right now:

More than one option there… Discussion is about how to create array of numbers from 1 to 10

``````var num = 10,
dynar = [...Array(num)].map((_,i) => ++i+"");
console.log(dynar);
``````
``````Array.apply(null, new Array(10)).map(function(el, i) {return ++i + ""})
``````

Also there is Array.from()

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.