Last active
March 22, 2016 19:26
-
-
Save deyindra/a4da9eb9f67b5d2a7036 to your computer and use it in GitHub Desktop.
RadomValueFromArrayBasedOnWeightAge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//smallest element greater than or equal to key | |
public static <T extends Comparable<T>> int findCeil(final T[] array, final T key){ | |
int low=0; | |
int high = array.length-1; | |
while (low<high){ | |
int mid = low + (high-low)/2; | |
if(key.compareTo(array[mid])>0){ | |
low = mid+1; | |
}else{ | |
high = mid; | |
} | |
} | |
if(array[low].compareTo(key)>=0){ | |
return low; | |
}else{ | |
return -1; | |
} | |
} | |
public static <T> T getRandomObjectWithGivenProbability(T[] array, Integer[] frequency){ | |
Integer[] prefix = new Integer[frequency.length]; | |
prefix[0] = frequency[0]; | |
for(int i=1;i<prefix.length;i++){ | |
prefix[i]=prefix[i-1]+frequency[i]; | |
} | |
Random r = new Random(); | |
Integer rand = r.nextInt(prefix[prefix.length-1])+1; | |
int index = findCeil(prefix,rand); | |
return array[index]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment