Akamai Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
why do we need rand(3) -3 in the statement return (3*rand(3) + rand(3) -3)?????
isnt 3*rand(3) sufficient???
3*rand(3) gives you 3 possibilities:
(3*1), (3*2) or (3*3)
=
3, 6, or 9
3*rand(3) - 3 gives you 3 possibilities:
(3-3), (6-3), (9-3)
=
0, 3, 6
3*rand(3)+rand(3)-3 gives you 9 possibilities:
(0+1), (0+2), (0+3), (3+1), (3+2), (3+3), (6+1), (6+2), (6+3)
in other words
1, 2, 3, 4, 5, 6, 7, 8, 9
Checks out.
Define a 3x3 matrix called A. Assign a value in range [1...9] to each entry of the matrix. Call rand(3) twice, and call the results i and j. Return the value corresponding to A[i][j]. Each outcome has probability 1/9.
no_of_times = rand(3);
if(no_of_times == 1){
return rand(3);
}
else if(no_of_times == 2){
return rand(3) + rand(3);
}
else{
return rand(3) + rand(3) + rand(3);
}
(rand(3) -1)*3 + (rand(3) - 1)*1 + 1
Do it as you would generate a number in base 3 number.
Example:
Just for the example lets say rand(3) generates numbers 0,1,2 and we are looking form numbers from 0-8 (rand(9)). In base 3 system the max number with length 2 will be 22 = 2*3^1 + 2*3^0 = 2*3 + 2*1 = 8 (eq1). So we just do generate the number in base 3 and find what it is:
in eq1 we change the numbers: rand(9) = rand(3)*3 + rand(3)*1
so now changing rand(3) return 1-3, and rand(9) must return 1-9
and final equation is: rand(9) = (rand(3) -1)*3 + (rand(3) - 1)*1 + 1
the solution will need to call the function random(3) 2 times......
first divide numbers from 1 to 9 into three equal size buffers......1-3...4-6....7-9.
Each buffer is containing exactly 3 numbers.
Now write the function random(9) as:
int random(9)
{
int bufferNo=random(3);
// if bufferNo=1,choose first else if 2 choose buffer 2 else choose buffer 3.
// again call random(3) to choose number in the chosen buffer and return that number
}
switch(rand(3))
- Anonymous August 10, 2012case 1:
rand(3)
case 2:
3 + rand(3)
case 3:
6 + rand(3)