Oraib Abo Rob
Oraib Abo Rob

Reputation: 67

How to create a random array with a specific range

I want to create a random array with 6 elements from (0-300) and the distance between the number and the next one is 20 , i mean ( 0,20,40,60,...,300)

here is my code to create 6 random array , but not in specific difference

in JS

var myNumArray = randomArray(6,0,300);
function random_number(min,max) {

return (Math.round(((max-min)) * Math.random() + min));
 }

function randomArray(num_elements,min,max) {

var nums = new Array;

for (var element=0; element<num_elements; element++) {
    nums[element] = random_number(min,max);
}

Upvotes: 0

Views: 85

Answers (1)

LdiCO
LdiCO

Reputation: 577

Since --i assume from your example-- the distance is fixed to 20, you could just use 15 as limit (instead of 300), then multiply random_number by 20 at the end.

Here how your code should like : (working exemple here )

var myNumArray = randomArray(6,0,15);

function random_number(min,max) {
    return (Math.round(((max-min)) * Math.random() + min));
}

function randomArray(num_elements,min,max) {

    var nums = new Array;
    for (var element=0; element<num_elements; element++) {
        nums[element] = random_number(min,max)*20;
    }
}

This give the wanted result. You can also adjust it to make the distance not hard coded :

// distance variable declaration;
// ...
nums[element] = random_number(min,max)*distance;

Upvotes: 3

Related Questions