0

I'm doing a lottery system and I need to make sure that each Array is ​​different. This is my code:

var intNumberOfBets = 10;
    let aLotteryTicket=[];
    let aData = [];

        for(intI = 0; intI <intNumberOfBets; intI++){
        let oCasilla ={};
         oCasilla.block=[]; 

 for(intI = 0; intI <intNumberOfBets; intI++){
            let oCasilla ={};
             oCasilla.block=[];

Each "lottery ticket" has an array with 5 numbers. They can have the same numbers as others but in different positions.

          for (let intB=1;intB<=5;intB++)
        {  
             for(let intA=1;intA<=50; intA++){  aLotteryTicket.push(intA); }
            oCasilla.block.push(aLotteryTicket.splice(parseInt(Math.random()*aLotteryTicket.length),1)); // ADD 5 NUMBERS RANDOMLY TO ARRAY
        };
        oCasilla.block.sort(function (a,b){ return (parseInt(a)-parseInt(b));});

        aData.push(oCasilla);

        alert(aData[intI].block); // show generated arrays

        }//END FOR

How can I prevent each array from being the same as another, before adding it to my final Array aData[]?

Example:If i add the array 5,6,7,8,9 to oCasilla.block=[]; , i need to check that there is not another 5,6,7,8,9 in oCasilla.block=[];

Thanks in advance

3
  • 1
    Could you give examples of allowable and forbidden tickets? It's not quite clear what you mean. Commented Oct 25, 2018 at 14:49
  • Can you use underscore? I'd just make an array with valid numbers and then repeatedly use _.shuffle and _.first on it. Commented Oct 25, 2018 at 15:02
  • If i add the array 5,6,7,8,9 to oCasilla.block=[]; , i need to check that there is not another 5,6,7,8,9 in oCasilla.block=[]; Commented Oct 25, 2018 at 15:04

1 Answer 1

1

You can use a set of string representations (numbers separated by comma built using join(',')) of your tickets to keep track of what was added, and only add if a ticket was not previously created.

function generateTicket() {
  // generate an array with 5 unique random numbers
  let a = new Set();
  while (a.size !== 5) {
    a.add(1 + Math.floor(Math.random() * 50));
  }
  return Array.from(a);
}


let oCasilla = {
  block: []
};
let addedTickets = new Set(); // add stingified ticket arrays here

// add 10 unique tickets to oCasilla.block
while (oCasilla.block.length !== 10) {
  const ticket = generateTicket();
  if (!addedTickets.has(ticket.join(','))) {
    oCasilla.block.push(ticket);
    addedTickets.add(ticket.join(','));
  }
}

console.log(oCasilla);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.