mathematical.coffee
mathematical.coffee

Reputation: 56935

Javascript - generate more than one random numbers without loop

I want to generate an array with n random numbers (i.e. n calls to Math.random()). I don't care about whether they are unique or not.

Currently I'm using a loop:

let numbers = [];
for (let i = 0; i < n; ++i) {
    numbers.push(Math.random());
}

I'd just like to know if this can be vectorised - for example in other languages I'd expect something like Math.random(n) to produce an array of n random numbers. Or is a loop the way to go in Javascript?

cheers.

Upvotes: 1

Views: 422

Answers (2)

user1612581
user1612581

Reputation: 1

In some cases, 'lazyness' may help. If you are not certain you'll need all the n generated numbers. you'd better go with a lazy implementation using yield ...

Upvotes: 0

Li0liQ
Li0liQ

Reputation: 11264

This way or another you will still get a loop somewhere underneath - even if there is any "vectorization" library for javascript, it will boil down to the loop.

Upvotes: 2

Related Questions