Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Have a look...
public static void main(String[] args) {
float START = 1;
float END = 2;
Random random = new Random();
for (int i = 1; i <= 100;i++) {
System.out.println(getRandomFloat(START, END, random));
}
}
private static float getRandomFloat(float start, float end, Random random) {
if (start > end) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
float range = end - start ;
float fraction = range * random.nextFloat();
float randomNumber = fraction + start;
return randomNumber;
}
OR
private static float getRandomFloat2(float start, float end, Random random) {
if (start > end)
throw new IllegalArgumentException("Start cannot exceed End.");
return (((end - start) * random.nextFloat()) + start);
}
printf's can be replaced by return statements
{{#include<time.h>
#include<math.h>
#include<stdio.h>
#define MIN 1
#define MAX 2
void main()
{
float a;
short i;
time_t sec1;
sec1=time(NULL);
srand(sec1);
a=log(rand());
if(a>=MIN&&a<=MAX)
printf("%f\n",a);
else
{
if(a>MAX)
{
while(a>MIN) a/=10;
}
if(a<MIN)a+=MIN;
printf("%f\n",a);
}
}
}}}
Program is in C-Sharp:
public double genrateRandom(int min, int max,int x)
{
Random rand = new Random();
return rand.NextDouble() * (max - min) / x + min;
}
static void Main(string[] args)
{
Console.WriteLine("Generating random number between 0 and 1");
Program p = new Program();
Console.WriteLine("Enter a number");
int m=Console.Read();
for (int x = 1; x < m;x++)
Console.WriteLine("Result : {0}",p.genrateRandom(1, 2,x));
}
good try. U did not use max? so if i give random(1,200), still returning 1.xxxx, below than 2
A java program is here.
System time used.
works fine...
import java.lang.Math.*;
public class getRandomNumber
{
public static double random(int min, int max)
{
double l = 0.0;
Long time = System.currentTimeMillis();
time = time%1000;
double t = time*1.0/1000;
l = min*1.0 + t;
return l;
}
public static void main(String args[])
{
System.out.println(random(1,2));
}
}
First generate a random number between 0 and 1 and add 1 to that result
- Anonymous March 28, 2012