3

When the user clicks, a random output from a set of outputs must be selected. The chances for one value needs to be higher than the other. For example, you click a button and you either receive Bronze, Silver, Gold, or Platinum. Obviously, if you click randomly, you should receive Bronze more than Silver, more than Gold, more than Platinum. For example, could it maybe look like this:

printRandom("Bronze", 30, "Silver", 20, "Gold", 10, "Platinum", 5, "You didn't get anything.");

Where the final result is when you were unlucky enough to get none. I've been having trouble with making one option more common than the other, not choosing a value in the first place. Thank you.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
CiY3
  • 134
  • 10
  • The Apache Commons RNG library has classes for this. – Shawn Jan 19 '22 at 18:51
  • Is 30 a weight or a percentage? If it's meant to be a weight then "You didn't get anything" is missing it's weight. Otherwise, are we to assume it's 35%? – candied_orange Jan 19 '22 at 20:35
  • I just put the numbers to signify how likely an option is. Since 30 is more than 20, 30 will be chosen more. – CiY3 Jan 20 '22 at 15:17

1 Answers1

0

If you want to keep it simple, you could do the following:

int random = Math.random();

if (random < 0.05) { // 5/100
  return "Platinum";
} else if (random < 0.1) { // 10/100
  return "Gold";
} else if (random < 0.2) { // 20/100
  return "Silver";
} else if (random < 0.3) { // 30/100
  return "Bronze";
} else {
  return "You didn't get anything.";
} 
gru
  • 2,319
  • 6
  • 24
  • 39
  • The early returns eat into the likely hood of later returns. You'll get Platinum 5%, Gold 5%, Silver 10%, Bronze 10%. I don't think that is what was intended. – candied_orange Jan 19 '22 at 21:12
  • No, not really. I think I can fix this by instead setting a string value instead of returning it, so that there is a chance to overwrite the platinum / gold etc. – CiY3 Jan 27 '22 at 01:05