Pergunta de entrevista da empresa Amazon

Rand(7) from Rand(5)

Respostas da entrevista

Sigiloso

2 de dez. de 2011

int rand7() { while(1) { int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1); if(n == 0) continue; return n; } } The rand5()%2 will generate 0 and 1 with equal probability and we need 3 bits since we are going from 000 upto 111. So we call this function thrice for each bit position.

3

Sigiloso

8 de fev. de 2012

Above answer is not correct because 0 is not returned. We need equal probability for all 0, 1,2,3,4,5,6. The modified would be: int rand7() { while(1) { int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1; if(n==0) continue; return n-1; } }

1

Sigiloso

26 de out. de 2011

Sorry this UI posts without warning int RandBin() { int rand5Res = Rand5(); return rand5Res < 2 ? 0 : rand5Res < 4 ? 1 : RandBin(); } And then use RandBin() to implement Rand7; int Rand7() { int rand = RandBin() << 2 | RandBin() << 1 | RandBin(); return rand < 7 ? rand : Rand7(); }

3

Sigiloso

26 de out. de 2011

The simple solution is to implement RandBin() using Rand5(). int RandBin() { }

1

Sigiloso

7 de jul. de 2016

int r = rand5() *5 + rand5() while (r>=21){ r = rand5() *5 + rand5(); } return r%7;

Sigiloso

6 de ago. de 2012

Java: Random r = new Random(); r.nextInt(5)+r.nextInt(5)%3

Sigiloso

20 de nov. de 2012

what about calling rand(5) 7 times adding it then % 7 ( rand5() + rand5() + rand 5() + rand5() + rand5 () + rand5() + rand5() ) % 7 -suhane

1