0

So I want to create a switch statement with each case having a different probability of being picked.

case 1 needs to be:

2 times as likely to occur as case 2

4 times as likely to occur as case 3

16 times as likely to occur as case 4

256 times more likely to occur as case 5

How would i go about creating these cases in java?

Jackson M
  • 1
  • 1
  • 1
    Why a switch? An `if` seems like it would make a lot more sense here. – Carcigenicate Oct 16 '19 at 19:32
  • there is already a thread on this topic.. [click](https://stackoverflow.com/questions/8183840/probability-in-java) Hope it'll help you. – Bltzz Oct 16 '19 at 20:51
  • I just tend to use switch statements for these types of random problems. If i were to use an if statement, what conditions should i use? – Jackson M Oct 17 '19 at 15:33

1 Answers1

0

That's a very weird question. If you're doing it for some practical purpose, and not as a puzzle I urge you to rethink your approach. Anyway, it's a nice little puzzle.

Here's one way you could do it - generate a random integer, then count the number of leading zeroes.

  • There's a 1/2 chance of having zero leading zeroes (1)
  • There's a 1/4 chance of having 1 leading zeroes (01)
  • There's a 1/8 chance of having 2 leading zeroes (001)
  • There's a 1/16 chance of having 3 leading zeroes (0001)
  • There's a 1/32 chance of having 4 leading zeroes (00001)
  • There's a 1/64 chance of having 5 leading zeroes (000001)
  • etc

You could then switch on this number.

Of course there's a chance you'll get a number you don't have a case for (like 32). In that case, you'd probably need generate a new number and try again.

Malt
  • 28,965
  • 9
  • 65
  • 105