EMC Interview Question
Software Engineer / Developersint method()
{
for(int i=1;i<=10;i++)
{
if(i<=4)return a;
elseif(i<=9)return b;
else return c;
}
}
Given K discrete events with different probabilities P[k], produce a random value k consistent with its probability.
The obvious way to do this is to preprocess the probability list by generating a cumulative probability array with K+1 elements:
C[0] = 0
C[k+1] = C[k]+P[k].
Note that this construction produces C[K]=1. Now choose a uniform deviate u between 0 and 1, and find the value of k such that C[k] <= u < C[k+1]. Although this in principle requires of order \log K steps per random number generation, they are fast steps, and if you use something like \lfloor uK \rfloor as a starting point, you can often do pretty well.
import java.util.Random;
/**
*
*/
/**
* @author Lazycoder
*
*/
public class Percentage {
/**
* @param args
*/
public static void main(String[] args) {
Random rand = new Random();
int i = rand.nextInt(10);
if(i < 4){
System.out.println("A");
}else if(i < 9){
System.out.println("B");
}else{
System.out.println("C");
}
}
}
use random number generation; then %10; then 0~4 -> A, 5~8 -> B, 9 -> C
- syrus August 13, 2010