Given a list of countries with population, how do you select random country from this list. Higher the population higher the probability of selection
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/RandomCountrySelectionByPopluation.java
public int getRandom(int []arr){
int sum[] = new int[arr.length];
sum[0] = arr[0];
int n = arr[0];
for(int i=1; i < sum.length; i++){
sum[i] = sum[i-1] + arr[i];
n += arr[i];
}
int ran = (int)(Math.random()*n + 1);
int low = 0;
int high = arr.length-1;
int mid = (high + low)/2;
while(true){
if(sum[mid] >= ran && (mid-1 == -1 || sum[mid-1] < ran)){
break;
}
if(sum[mid] > ran){
high = mid-1;
}else{
low = mid+1;
}
mid = (high + low)/2;
}
return mid;
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/SelectMRandomNumbersInStream.java
public class SelectMRandomNumbersInStream {
public int[] selectRandom(int arr[],int m){
int result[] = new int[m];
for(int i=0; i < m ;i++){
result[i] = arr[i];
}
for(int i=m ; i < arr.length; i++){
int random = (int)(Math.random()*i) + 1;
if(random <= m){
result[random-1] = arr[i];
}
}
return result;
}
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/ShuffleArray.java
public class ShuffleArray {
public void shuffle(int arr[]){
for(int i=arr.length-1; i>=0; i--){
int random = (int)(Math.random()*(i+1)) ;
System.out.print(random + " ");
swap(arr,random,i);
}
}
private void swap(int arr[],int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/RandomCountrySelectionByPopluation.java
public int getRandom(int []arr){
int sum[] = new int[arr.length];
sum[0] = arr[0];
int n = arr[0];
for(int i=1; i < sum.length; i++){
sum[i] = sum[i-1] + arr[i];
n += arr[i];
}
int ran = (int)(Math.random()*n + 1);
int low = 0;
int high = arr.length-1;
int mid = (high + low)/2;
while(true){
if(sum[mid] >= ran && (mid-1 == -1 || sum[mid-1] < ran)){
break;
}
if(sum[mid] > ran){
high = mid-1;
}else{
low = mid+1;
}
mid = (high + low)/2;
}
return mid;
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/SelectMRandomNumbersInStream.java
public class SelectMRandomNumbersInStream {
public int[] selectRandom(int arr[],int m){
int result[] = new int[m];
for(int i=0; i < m ;i++){
result[i] = arr[i];
}
for(int i=m ; i < arr.length; i++){
int random = (int)(Math.random()*i) + 1;
if(random <= m){
result[random-1] = arr[i];
}
}
return result;
}
}
https://github.com/mission-peace/interview/blob/master/src/com/interview/random/ShuffleArray.java
public class ShuffleArray {
public void shuffle(int arr[]){
for(int i=arr.length-1; i>=0; i--){
int random = (int)(Math.random()*(i+1)) ;
System.out.print(random + " ");
swap(arr,random,i);
}
}
private void swap(int arr[],int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}