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.