Generate An Array Of Consecutive Numbers That Are Spaced Out Between A Minimum And Maximum
For Example if We Want 5 Numbers Between 1 - 50 With No Less Than a 2 Digit Spread Between Numbers but No More That a 4 Digit Spread Between Numbers ...
Home
Short:
/* --------------------------------------------------------------------- GENERATE AN ARRAY OF CONSECUTIVE NUMBERS THAT ARE SPACED OUT BETWEEN A MINIMUM AND MAXIMUM. FOR EXAMPLE IF WE WANT 5 NUMBERS BETWEEN 1 - 50 WITH NO LESS THAN A 2 DIGIT SPREAD BETWEEN NUMBERS BUT NO MORE THAT A 4 DIGIT SPREAD BETWEEN NUMBERS ... non_consecutive_rand_numbers(5, 1, 50, 2, 4); --------------------------------------------------------------------- */ function rand_numbers_spaced(how_many, first_number, last_number, min_increment, max_increment){ let min = 0, max = 0; let next = (first_number - min_increment); let arr_ret = []; // loop until we gather [how_many] random numbers while(arr_ret.length < how_many){ // set the next min and max number for random number min = (next + min_increment) max = (next + max_increment) // pick a random number between min and max next = Math.floor(Math.random() * (max - min + 1)) + min; // if next # to add to array < last desired number [last_number] if(next <= last_number){ // add this random number to the array arr_ret.push(next); }else{ return arr_ret; } // exit if we have aquired desired number of numbers if(arr_ret.length > how_many){ return arr_ret; } } return arr_ret; }
source code home