Goldman Sachs Interview Question
SDETsCountry: India
Interview Type: Phone Interview
The above code doesn't handle the uniqueness.
public static void main(String...args){
List<Integer> numbers = new ArrayList<Integer>();
Test test = new Test();
for(int i=0; i< 5; i++){
int random = test.generateRandom(5);
while(numbers.contains(random)){
random = test.generateRandom(5);
}
numbers.add(random);
}
for(int i = 0; i< numbers.size(); i++){
System.out.println(numbers.get(i));
}
}
private int generateRandom(int range){
Random random = new Random(System.currentTimeMillis());
return random.nextInt(range);
}
It is not necessary to use new Random(System.currentTimeMillis()) here, because new Random() does the same thing.
public Random() {
this(System.currentTimeMillis());
}
/**
* Creates a new pseudorandom number generator, starting with the
* specified seed, using <code>setSeed(seed);</code>.
*
* @param seed the initial seed
*/
public Random(long seed) {
setSeed(seed);
}
If java.util.Random is allowed to use, we could implement it like this:
/**
* Get random number without range.
*
* @return random number
*/
int getRandom() {
return new Random().nextInt();
}
/**
* Get random number with range.
*
* @param min
* @param max
* @return random number
*/
int getRandom(int min, int max) {
return new Random().nextInt((max - min) + 1) + min;
}
Java provides library to create random number generator and generate random numbers. I have used system current time in milliseconds as seed so that even when JVM is re-booted there is very high chance that numbers will not be repeated. If one has to be hundred percent sure , then we will need to write all the random numbers to a file before JVM is shut down and then compare those while generating random numbers.
- praveenkcs28 October 27, 2014