Facebook Interview Question
Software Engineer / DevelopersCountry: -
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.
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;
}
}
}
In java you can do it as so:
public static int getRandom(Random r, int x)
{
return ((r.nextInt(100)) < x) ? 0 : 1;
}
There are 0-64 (65) chances that the generator will end up returning 1, and 65-99 (35) chances it will return 0.
/*
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;
}
here is the solution test it with System.err.println(Arrays.toString(generateProbality(65, 100)));
public static int[] generateProbality(int n, int max) {
if (n > max)
return null;
int[] result = new int[max];
for (int i = 0; i < result.length; i++) {
result[i] = 0;
}
Random random = new Random();
for (int i = 0; i < n; i++) {
int index = random.nextInt(max);
if (result[index] == 0) {
result[index] = 1;
} else
i--;
}
return result;
}
the easiest way i feel...
- Amit July 16, 2013int myrand(int x)
{
int y=rand()%100;
if(y<x)
return 1;
return 0;
}