## Facebook Interview Question Software Engineer / Developers

- -3of 9 votes
Given a number x, less than 100. How will you generate true with probability x/100. So if x = 65, how will you generate true with probability 65/100. You can represent true by 1 and false by 0.

**Country:**-

Incorrect.

As stated on xhxtxtxpx:x/x/xwxwxwx.xcxpxlxuxsxpxlxuxsx.xcxoxmx/xreference/cstdlib/RAND_MAX/ (remove the x's)

"This value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation."

If your library uses 32767, then each number from 0 to 67 has a 328/32768 chance of being set to your y, and everything else from 68 to 99 only has a 327/32768 chance.

```
/*
Given a number x, less than 100. How will you generate true with probability x/100. So if x = 65, how will you generate true with probability 65/100. You can represent true by 1 and false by 0.
Developed BY:Suman Roy
Emil : email.suman.roy@gmail.com
*/
#include<iostream>
#include<stdlib.h>
#include<ctime>
using namespace std;
int main(){
int x, temp;
std::cout<<"Enter x\n";
std::cin>>x;
int count1=0;
int count2=0;
for ( int i=0;i<100;i++){
if ( x>100 ) {
std::cout<<"X is greater than 100 \n";
exit(EXIT_SUCCESS);
}
temp=rand() % 100 + 1;
if ( temp <= x ){
count1++;
std::cout<<"true="<<1<<std::endl;
}
else{
count2++;
std::cout<<"False="<<0<<std::endl;
}
}
std::cout<<"true occured="<<count1 <<"\n"<<"False occured="<<count2<<std::endl;
return 0;
}
```

```
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<time.h>
using namespace std;
int main(void)
{
srand(time(NULL));
double prob = ((double)rand())/RAND_MAX; //preserving the assumed uniform-random-nature of output
int input;
cin >> input;
if (prob < input*0.01) cout << "True" << endl;
else cout << "Flase" << endl;
return 0;
}
```

```
public class Probability {
public static void main(String[] args) {
int x = 5;
// write a function to generate true with a probability of 65/100
for (int i = 0; i < 10; i++) {
System.out.println(generateTrue(x));
}
}
public static boolean generateTrue(int x) {
double random = Math.random() * 100;
if (random < x) {
return true;
} else {
return false;
}
}
```

}

the easiest way i feel...

- Amit on July 16, 2013 Edit | Flag Replyint myrand(int x)

{

int y=rand()%100;

if(y<x)

return 1;

return 0;

}