D
Digital Puer
I have an algorithmic question (not necessarily tied to Java).
Suppose I have the text from a newspaper and want to choose
a letter from the text with proportional probability. For example,
if the letter 'e' occurs, say, 50 times out of a text of 150
characters, then 'e' will be chosen with probability 1/3.
What is the best way to code this? I could set up an if-elseif ladder
like this:
x = random number [1 to total number of letters]
if (1 < x <= 10) /* 10, for example, because 'a' occurred 10 times */
choose 'a'
else if (10 < x <= 14) /* because 'b' occurred 4 times */
choose 'b'
This seems extremely tedious. Is there a better way?
Suppose I have the text from a newspaper and want to choose
a letter from the text with proportional probability. For example,
if the letter 'e' occurs, say, 50 times out of a text of 150
characters, then 'e' will be chosen with probability 1/3.
What is the best way to code this? I could set up an if-elseif ladder
like this:
x = random number [1 to total number of letters]
if (1 < x <= 10) /* 10, for example, because 'a' occurred 10 times */
choose 'a'
else if (10 < x <= 14) /* because 'b' occurred 4 times */
choose 'b'
This seems extremely tedious. Is there a better way?