During an interview I was asked to implement a random generator in java without using any existing random number libraries that takes as an argument int n, and returns a random number between 0 and n. This was the implementation I provided:
public static int random(int n) {
int r = 0;
for (int i =0; i <n;i++) {
r+=helper();
}
return r;
}
// helper that returns 0 or 1
private static int helper() {
long t = System.nanoTime();
if (t%2 == 0) {
return 1;
} else {
return 0;
}
}
He said it's not right but he wouldn't tell me what he was expecting. Why did he say it's wrong? How would you have done it differently?