Skip to content

Instantly share code, notes, and snippets.

@hiroto3432
Created December 16, 2017 07:26
Show Gist options
  • Save hiroto3432/e71ef4689f473b95b869eb444961b241 to your computer and use it in GitHub Desktop.
Save hiroto3432/e71ef4689f473b95b869eb444961b241 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Random;
class WeightedRandom2{
public static void main(String args[]){
ArrayList<Factor> fact = new ArrayList<>();
ArrayList<Integer> result = new ArrayList<>();
fact.add(new Factor("★5",2));
fact.add(new Factor("★4",12));
fact.add(new Factor("★3",86));
int fs = 0;
while(fs<fact.size()){
result.add(0);
fs++;
}
int trials = 10000000;
for(int n=0;n<trials;n++){
int r = getRandom(fact);
result.set(r,result.get(r)+1);
}
System.out.println("result");
System.out.println("trials:"+trials+" times");
for(int n=0;n<fact.size();n++){
System.out.println(fact.get(n).name+":"+result.get(n));
}
}
private static int sum(ArrayList<Factor> f){
int n=0;
int total=0;
while(n<f.size()){
total += f.get(n).ratio;
n++;
}
return total;
}
private static int getRandom(ArrayList<Factor> f){
int sumWeight = sum(f);
Random rnd = new Random();
int val = rnd.nextInt(sumWeight);
int n = -1;
do{
n++;
val -= f.get(n).ratio;
}while(val>=0 && f.size()>n);
return n;
}
}
class Factor{
String name;
int ratio;
Factor(String name,int ratio){
this.name = name;
this.ratio = ratio;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment