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
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
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
You can break this down into smaller; logical functions.
determineChance
~ Get the chance, and update the documentgetRandomChance
~ Find a chance, where the random value is 0formatMessage
~ Format the message, based on the chance datarandInt
~ Generate a random integerHere is an example of a 1/100 roll: