CareerCup Randomly return a number inside of this range

265 篇文章 1 订阅
86 篇文章 0 订阅

Give a min and max of an integer array, write a function to randomly return a number inside of this range, but not in the list. Also write a class that contains this function.

---------------------------------------------------------


Some people have suggested making an array of the numbers we do not have in the given list. This array can be too big. 

We can have this algoirthm: 
1. Sort the given list. It takes time O(nlogn) 
2. Instead of creating an array we can just get the size of the array, i.e., number of elements which are not present in the given list. It will be 
size = (max-min+1) - (number of distinct numbers in the list) 

3. Now we can get a random number k in the range [1,size] 

4. Now we just need to find the kth number among the numbers which are not present in the given list. We have not created the array of missing numbers. So we will find the kth number among the missing numbers using the given list as follows: 
a) take curr = min 
b) take num = curr + k - 1 (taking k to bestarting from 1) 
c) do binary search to find element in the list which is the rightmost element less than or equal to num. Label it as lower_element 
If no such element exists, then num is less than first element in the list, so num is the answer. 
Otherwise, 
(i) count the number of elements from lower_element in this traversal to the lower_element in previous traversal (if first traversal, count number of elements from starting) 
(ii) k = (count in step (i)) 
(iii) num = num + k 


Example: 

List is {10, 20, 40, 60, 80} //taking sorted list for convenience. 
Range is 1-100 

Step 2. 
size = (100-1+1) - 5 
= 95 

Step 3. 
Random number generated = 50 

Step 4. 

a) curr = 1 
b) num = 1+50-1 = 50 
c) 
First traversal: 
search for 50 in the given array. 
lower_element = 40 
i) count = 3 
ii) k = 3 
iii) num = 50+3 = 53 

Second traversal: 
search for 53 in the given array after 40. 
There is no lower_element now. 

So the answer is 53. 

Basic Assumption: We have a function that generates a pure random number from 1 to n.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值