Paco
Paco

Reputation: 5

Compare arrays in loop - javascript

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

Upvotes: 0

Views: 69

Answers (1)

slider
slider

Reputation: 12990

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);

Upvotes: 1

Related Questions