skip to Main Content

So, I have 4 chances (chance1, chance2, etc.). I want to check if one chance is equal to one, but none of the other ones are one. I know I could just check every single one, but I’m eventually going to add more and more chances, and the list will be really long and annoying to deal with.

var chance1 = Math.floor(Math.random() * 10) + 1
var chance2 = Math.floor(Math.random() * 100) + 1
var chance3 = Math.floor(Math.random() * 1000) + 1
var chance4 = Math.floor(Math.random() * 10000) + 1

if (chance1 === 1) {
  document.body.innerText = "Red - 1 in 10"
  document.body.style.backgroundColor = "red"
}

if (chance2 === 1) {
  document.body.innerText = "Orange - 1 in 100"
  document.body.style.backgroundColor = "orange"
}

if (chance3 === 1) {
  document.body.innerText = "Yellow - 1 in 1,000"
  document.body.style.backgroundColor = "yellow"
}

if (chance4 === 1) {
  document.body.innerText = "Green - 1 in 10,000"
  document.body.style.backgroundColor = "green"
}

Again, I tried checking every single value, it works, but I think it would be best to have a more efficient way to this.

2

Answers


  1. So you want to update the page to show the least likely event that happened?

    Store your chances in an array, along with the color that corresponds with that chance. There are several ways to do this, one would be to store them as an object that looks like this

    {
      chance: 1000,
      color: 'green',
    }
    

    Store the chances in reverse order, meaning test the least likely scenario first, as opposed to checking the most likely and then overwriting afterward.

    So the full code might look something like this

    const chances = [
      { chance: 10000, color: 'green' },
      { chance: 1000, color: 'yellow' },
      { chance: 100, color: 'orange' },
      { chance: 10, color: 'red' },
    ];
    
    function determineChance() {
      for (let {chance, color} of chances) {
        const roll = Math.floor(Math.random() * chance) + 1;
        if (roll === 1) {
           const capColor = color[0].toUpperCase() + color.slice(1);
           document.body.innerText = `${capColor} - 1 in ${chance}`;
           document.body.style.backgroundColor = color;
           
           return;
        }
      }
      
      // If here, no hits
      document.body.innerText = 'No hits';
    }
    
    determineChance();
    Login or Signup to reply.
  2. You can break this down into smaller; logical functions.

    1. determineChance ~ Get the chance, and update the document
    2. getRandomChance ~ Find a chance, where the random value is 0
    3. formatMessage ~ Format the message, based on the chance data
    4. randInt ~ Generate a random integer
    const chanceArr = [
      { limit: 10_000 , color: 'green'  },
      { limit:  1_000 , color: 'yellow' },
      { limit:    100 , color: 'orange' },
      { limit:     10 , color: 'red'    },
    ];
    
    
    const determineChance = () => {
      const chance = getRandomChance();
      document.body.innerText = formatMessage(chance); // Always show message
      if (chance) {
        document.body.style.backgroundColor = chance.color; // If applicable
      }
    };
    
    const getRandomChance = () => chanceArr.find(({ limit }) => {
      const randomIndex = randInt(limit);
      console.log(JSON.stringify({ limit, randomIndex })); // DEBUG
      return randomIndex === 0;
    });
    
    const formatMessage = (chance) => chance
      ? `${capitalize(chance.color)} - 1 in ${chance.limit.toLocaleString()}`
      : 'No hits';
    
    const randInt = (max) => Math.floor(Math.random() * max);
    const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
    
    determineChance(); // Main entry-point

    Here is an example of a 1/100 roll:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search