## Google Interview Question

Software Developers**Country:**United States

Interesting problem. There can be at least 2 ways to get it done.

The trivial one:

```
def getRandomOdd( min, max){
r = random()
while ( (n = r.num(min,max)) % 2 == 0 );
n // return n
}
```

The problem is - not really uniform, in some sense. To generate uniform, we use a reverse map:

y_min, y_max : such that

2 * y_min + 1 -> min

2 * y_max + 1 -> max

If min, max are not that way, we change them by something. Now we have a cleaner solution:

```
def getRandomOdd( min, max){
r = random()
y_min = min/2
if ( 2 /? max ){ max - 1 }
y_max = max/2
2 * r.num( y_min, y_max ) + 1
}
```

C++ solution

```
int getRandomOdd(int left, int right)
{
// Exclude right-most odd number
right = right % 2 == 1 ? right - 1 : right;
// Error checking
if (left >= right) return 0;
// Divide out even numbers and shift to the left
int leftRng = rand() % ((right - left + 1) / 2) - 1;
// Check for left even shift
int leftShift = left % 2 == 0 ? 1 : 0;
// Shift it back to the right and expand to all odd numbers
return left + leftShift + 2 * (leftRng + 1);
}
```

New to this platform .writing a c program instead of function .can anyone tell if my code is correct or not.

```
#include<stdio.h>
#include<time.h>
int main()
{
int min,max,a[10],b[10],i,var1=0,diff;
int j,max_arr;
time_t t;
printf("enter min ad max");
scanf("%d %d",&min,&max);
printf("enter any number between min and max excluding max");
diff=max-min;
printf("\ndiff is %d",diff);
for(i=0;i<diff;i++)
{
scanf("%d",&var1);
if(var1>=min && var1 <max)
{
a[i]=var1;
}
else
{
i--;
}
printf("i is %d",i) ;
}
for(i=0;i<diff;i++)
{
printf("\n b is %d",a[i]);
}
for(i=0;i<diff;i++)
{
if(a[i]%2!=0)
{
b[j]=a[i];
j++;
}
}
srand((unsigned) time(&t));
i=rand()%j;
printf("rand no is %d",b[i]);
}
```

In CPython 2:

Why does this work?

- Generating odd random numbers in CPython 2 April 12, 2017I assume that it works like randint so "high" is included in the range. We don't want low to be bigger than high and if low is equal to high we want it to be an odd number. That's what the assertion does.

Now for the limits in randint(ri). If low is odd as in 2 * k / 1 then low / 2 = k so it's good. if low is even as in 2 * k then low / 2 = k so it's also good. If high is odd as in 2 * k + 1 then (high - 1) / 2 = k so it's good and if it is even as in 2 * k then (high - 1) / 2 = k - 1 which is also good since 2 * k - 1 = 2 * (k - 1) + 1 is the largest odd number in this range.