Google Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
/**
* @Description: random number generator
* @param seed
* @param num how many numbers to generator
*/
static void randomGenerator(int seed, int num) {
while (num-- > 0) {
String md5 = getMD5(String.valueOf(seed));
int random = 0;
for (int i = 0; i < md5.length(); i++)
random += md5.charAt(i) - 'A';
System.out.println(random);
seed++;
}
}
/**
* @Description: generate md5
* @param input
* @return
*/
static String getMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
return hashtext;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
There are two problems with this solution.
- ravio June 01, 20141.It's not a random number generator. It means that the number you generated is not random. It depends on the time.
2. The reason why you always get 0 firstly is that any positive mod 1 is 0. In your case, you have the first number mod i where i is always 1 initially.
The corrent way to generate a ranom number is to use Linear congruential. You can check that out.