Examples of our Technical Assignments


Problem

You have been given a method int r5() which returns a number from 1 to 5. The return values are based on the following rules:

  1. The method returns a random number based on a random seed value (e.g. wind speed at random location at a random time)
  2. Each number from 1 to 5 has an equal probability of being returned

Derive a random method int r7() from r5() which returns a number from 1 to 7 and confirms to the rules above.

Analysis

The random seed value is just a distraction. The point is: you have a method that returns a random number. There is no known pure random number generator, which doesn’t repeat the sequence of its output. So, we have to trust r5() and have to drive from it to generate larger or smaller random number sets.

We could do the following:

1
2
3
4
5
public int r7(){ 
 
      return r5() + r5()%3; 
 
}

But quite clearly, the probability of the numbers 1, 2, 3, 4, 5 are higher than that of 6 and 7. Why? r5()%3 returns 0 for 1, 2 and 3.

Another solution could be to derive r2() from r5() as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int r2(){ 
 
        boolean discard = true; 
 
        do{ 
 
          int r = r5() 
 
          if r > 2 discard = false; 
 
        } while(discard); 
 
        return r; 
 
}

And, derive r7() to be an addition of r2() and r5() as follows:

1
2
3
4
5
public int r7(){ 
 
     return r5()+r2(); 
 
}

Or, you could derive r1() the way we did for r2(), and then derive r7() as the addition of r1() 7 times - 7 X r1(). Really, are you sure…ebay Java interview questions

This was asked at an interview for the position of Search Front-end Engineer at a leading e-commerce company. Feel free to leave your questions/solutions in the comments box below. Or send us a mail - tech at ideareboot dot com.

0 Response to “Examples of our Technical Assignments”


Leave a Reply