Home > Back-end >  How to avoid a condition from looping?
How to avoid a condition from looping?

Time:10-17

I have to code a console Bingo game for JavaScript. It is one of some exercices that I have to do before a Bootcamp that I will be taking part of, so take in mind that i'm a newbie. In case someone doesn't know the game:

  • You will have a "card" showing 15 numbers (not repeated and random)
  • Each turn a random number (bingo ball) will be shown.
  • The numbers are from 1 until 90, so either balls and bingo cards will have these numbers.
  • When a ball has the same number as one of the numbers from your card, the number of your card will be changed to an 'X'.

Now that I've explained it, my problem is the following: I have a function to generate generate a ball with a random number each turn. In order to know if a number was already out or not, I've created an array to push the numbers that were already out. This way we can make a loop with an if condition to check if the ball has the same value as the arrays[i] number. The way I've done it, starts well, but ends up messing the chrome's console... as close as it gets to have the 90 numbers in the array, it starts to iterate the array and generate random numbers until it finds the lasts numbers remaining.

I will paste the part of the code I'm talking about here below.

function bingo(){
   console.table(bingoCard);
   bombo();
   for (let i = 0; i < bingoCard.length; i  ){
      if (bola === bingoCard[i].number){
         bingoCard[i].number = 'X';
         bingoCard[i].matched = true;
      }
   }
   continuar = confirm('¿Continuar?');

   if (continuar === true){
      console.table(bingoCard);
      bingo();
   }else {
      return 'Hasta la próxima';
   }
}

function randomNum(){
   let min = 1;
   let max = 90;
   return Math.floor(Math.random() * (max - min)   min);
}
         
function bombo(){

   bola = randomNum();
   console.log(  bola   'antes de bucle'); //test
   for (let i = 0; i < numbersOut.length; i  ){
      if (bola === numbersOut[i]){
         bingo();
      }
   }
   numbersOut.push(bola);
   console.log(numbersOut);
   alert('Ha salido el número '   bola);   
}

CodePudding user response:

You can instead create an array with numbers from 1 to 90 and random shuffle it.

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i   1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Modern_method - if you want to understand this method

  • Related