Skip to content

Instantly share code, notes, and snippets.

@seraekim
Created November 28, 2017 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraekim/81f2d404e9c9f4ed3ffd2a6db5fc4137 to your computer and use it in GitHub Desktop.
Save seraekim/81f2d404e9c9f4ed3ffd2a6db5fc4137 to your computer and use it in GitHub Desktop.
Weighted Random lot
package org.srkim.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class WeightedRandom {
public static void main(String[] args) {
List<Integer> lot = new ArrayList<Integer>();
for (int i = 1; i < 46; i++) {
lot.add(i);
}
// all the numbers have the same percentage to be selected.
// now, add some weights on 2, 4 and 5.
// 2, 4 or 5 is selected with a probability of 30 in 72.
int[] a = { 1, 10, 1, 10, 10, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1};
int sum = 0;
for (int i : a)
sum += i;
Random r = new Random();
int s = r.nextInt(sum);
// System.out.println(s + " " + sum);
int prev_value = 0;
int current_max_value = 0;
int found_index = -1;
for (int i = 0; i < a.length; i++) {
current_max_value = prev_value + a[i];
boolean found = (s >= prev_value && s < current_max_value) ? true : false;
if (found) {
found_index = i;
break;
}
prev_value = current_max_value;
}
int selection = -1;
if (found_index != -1) {
selection = lot.get(found_index);
}
System.out.println(selection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment