Is there a better way to fill this array in Node.js?

Asked

Viewed 220 times

1

Below this my function of Node.js (I’m new at this), I would like to fill the array with random numbers (could be with everything else), is there any faster way to do this ? Of what I’m doing ?

QLearn.reset = function() {
       for (var a=0; a<100; a++) {
        for (var b=0; b<20; b++) {
            for (var c=0; c<100; c++){
                for (var d=0; d<QLearn.action; d++){
                    QL[a,b,c,d]=Math.random();
                }
            }
        }
    }
  • 1

    It is unclear what result you want to get... do you want to create a new array or modify an existing array? The array is of a single dimension or has arrays inside arrays?

  • Are arrays inside arrays var QL = [[],[],[],[]]; I want the function to initialize the array and fill it with random numbers. The important thing is that it does so as quickly as possible.

  • And the random numbers are any or between a default value? How many numbers per array?

  • ranging from 0 to 1 would be good, even if it was only with zeros would already be interesting, the important thing is that it is fast.

  • Okay, did you see my answer? That’s what you were looking for?

  • I was wondering, I’d still have to put for (var a=0; a<100; a++) {&#xA; for (var b=0; b<20; b++) {&#xA; for (var c=0; c<100; c++){ ????

  • My code supersedes all these for. The result is an array, with arrays inside, each with four random numbers from 0 to 1.

Show 2 more comments

1 answer

0

If you are in Node.js environment you can use modern Javascript and do something like this:

function randomArray(){
    return [...Array(4)].map(Math.random);
}
const start = +new Date(); 
var QL =  [...Array(100)].map(randomArray);
const end = (+new Date()) - start;
console.log(QL, end); // 2ms

This code generates 100 subarrays of 4 random numbers each.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.