Random Number with Range Probabilities

Hey @Kim!

This is pretty similar to these topics, but as there’s an opportunity to write new code, I’ll take the time to write it:

Nightbot uses JavaScript for its $(eval) commands, so that’s what we’ll be using here.

// this is our random number generator function
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
// first call of the function to determine the range, it'll return a number between 1 and 100
const range = random(1, 100);
// we first compute the output for the -30 to 0 range, it'll be overwritten if needed
let output = random (-30, 0);
// then we test if the range is over 20, or 20%, if it is we compute the output for the 0 to 40 range and overwrite the output
if (range > 20) {
  output = random(0, 40);
// then we test if the range is over 50%: 20% + 30%, if it is we compute the output for the 40 to 80 range and overwrite the output
if (range > 50) {
  output = random(40, 80);
// and finally, we test if the range is over 90%: 20% + 30% + 40%, , if it is we compute the output for the 40 to 80 range and overwrite the output
if (range > 90) {
  output = random(80, 100);
// and we end by returning the output
return output;

Since the command is basically all randomly generated numbers, we can define a random() function that we call every time we need it, it’ll return a number between min and max (both included) every time it’s called (need more details?).

I call it first to know which range I fall into, since it goes from 1% to 100%, I send 1 and 100 to random().
Then I generate the output for the first range, that has a 20% chance of happening: random(-30, 0).
After that I check if the range is the next one, so if I’m above 20%, and if that’s the case I overwrite the output with the next random() call, and I keep going until I’ve covered all the ranges.

For Nightbot we can save on characters by removing a lot of the syntax that will then be implied, this is when mistakes may show up the most, but it’s still fairly reliable if you understand the basics of Javascript well enough, and we also introduce some syntactic sugar to save a bit more on characters.

$(eval r = (a, b) => Math.floor(Math.random() * (b - a + 1) ) + a; p = r(1, 100); o = r(-30, 0); if (p > 20) { o = r(0, 40) } if (p > 50) { o = r(40, 80) } if (p > 90) { o = r(80, 100) } o;)

PS: if you need to save more characters, you can remove all the spaces I left in the command to help readability, except for the first one that comes after eval, you can also remove the very last semi-colon.