简体   繁体   中英

How to generate Random numbers, then exclude array of numbers

i would like to generate random numbers from 1-50, then exclude an array like; 4,7,10,20,35 etc

i tried this;

 let mainNum = 50 let exclNum = [4, 7, 10, 20, 35]; if (!exclNum.includes(mainNum)) { console.log(Math.floor(Math.random() * mainNum) + 1) }

but it still generates numbers that's still in the array, please is there anything i am missing?

Thanks for your response in advance

You need to generate the random number first, then check if it's in the array. Do this in a loop until it's not in the array.

 let mainNum = 50 let exclNum = [4, 7, 10, 20, 35]; let ranNum; while (true) { ranNum = Math.floor(Math.random() * mainNum) + 1; if (!exclNum.includes(ranNum)) { break; } } console.log(ranNum);

You are currently checking whether exclNum includes mainNum , which is 50.

Instead, generate the random number and check whether exclNum includes it:

 let mainNum = 50 let exclNum = [4, 7, 10, 20, 35]; while(!exclNum.includes((randomNum = Math.floor(Math.random() * mainNum) + 1))){ console.log(randomNum) break; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

A do... while loop is more concise

function myRandom(mainNum, exclude) {
    let r;
    do {
        r = Math.floor(Math.random() * mainNum) + 1;
    } while(exclude.includes(r))
    return r;
}

console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));

I'm going to give you two different approaches using rando.js to simplify the randomness and make it cryptographically secure.

  1. This could execute a ton of times before landing on a number that hasn't been excluded:

 var result; while([4, 7, 10, 20, 35].indexOf(result = rando(1, 50)) > -1); console.log(result);
 <script src="https://randojs.com/2.0.0.js"></script>

  1. This will fill up an array with allowed numbers and pick one of those.

 for(var nums = [4, 7, 10, 20, 35], i = 1; i <= 50; i++) nums.indexOf(i) + 1 ? nums.shift() : nums.push(i); console.log(rando(nums).value);
 <script src="https://randojs.com/2.0.0.js"></script>


If you want the plain javascript version of this stuff, here you go!

1)

 var result; var min = 1; var max = 50; while([4, 7, 10, 20, 35].indexOf(result = Math.floor(Math.random() * (max - min + 1)) + min) > -1); console.log(result);

2)

 var nums = [4, 7, 10, 20, 35]; var min = 1; var max = 50; for(var i = min; i <= max; i++) nums.indexOf(i) + 1 ? nums.shift() : nums.push(i); console.log(nums[Math.floor(Math.random() * nums.length)]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM