Help with making lottery simulator

I’m trying to make a program that will do a “lucky dipper a person” while also doing the same “for the lotto machine”. I’m wanting to see how many times this would need to run before the two arrays would be the same, or until the lottery is won.

However, the part I’m struggling with is how to avoid any duplicate numbers in the arrays using the Math.floor(Math.random() * 58 + 1) method. Here is what I’ve got so far, and is not avoiding duplicates as I hoped. Can somebody please tell me where I’m going wrong?

let myChoice = ,
lottoNumbers = ;

for (let i = 0; i < 6; i++) {
let myNumber = Math.floor((Math.random() * 58) + 1);
if (myNumber !== myChoice[0] || myChoice[1] || myChoice[2] || myChoice[3] || myChoice[4] || myChoice[5]) {
} else {
i -= 1;

console.log(myChoice.sort((function(a, b){return a-b})));

Wait, I think I’ve just figured it out… Is it because I didn’t put the “myNumber !==” between each “||”?

Never mind, that didn’t fix it :sob:

Figured it out!! I should have been using && instead of ||! :slight_smile:

If you want to compare something to 5 other things, then you would need to invoke the comparison 5 times right? But you only use it once.

1 Like

That, and also using && instead of || seems to have fixed it :slight_smile:

Another thing you can do is to abstract out a few things.

For example, testing whether you’ve already got a value in an array, that could be a completely separate function. That function would itself be simple and the remaining code would be simpler too.

In particular it avoids the mental gymnastics of figuring out whether all those boolean operations actually do the right thing. (Yeah you should be able to do it, but … you should probably avoid it)

if (contains(myvalues, x)) {

Alternatively you could make a function that removes a random value from a list, and returns it. (Swap its last value to the location of the removed value so that you don’t have to move all the values that follow) - and then you could use that to pop 6 values from a pool, no testing for duplicates required.

const pool = [1,2,3...]
const myvalues = []
for (let i = 0; i < 6; i++) {

Or if you already have some shuffling function available, you could shuffle and take 6.

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.