Created
December 16, 2017 07:26
-
-
Save hiroto3432/be560d71d6c4e643229f492ca14a7acf to your computer and use it in GitHub Desktop.
This file contains 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
import java.util.ArrayList; | |
import java.util.Random; | |
class WeightedRandom1{ | |
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 r = getRandom(fact); | |
System.out.println("result:"+fact.get(r).name); | |
} | |
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