From 6d538c3f2f2ee08b0b66fd36f6490ee3bbdb2524 Mon Sep 17 00:00:00 2001 From: Boyana Kantarska Date: Thu, 8 Nov 2018 13:55:36 +0200 Subject: [PATCH] Some simplifications were done. --- .../simpleslots/WeightedRandomGenerator.java | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/src/main/java/net/dasigns/simpleslots/WeightedRandomGenerator.java b/src/main/java/net/dasigns/simpleslots/WeightedRandomGenerator.java index eaf5cd8..25872f8 100644 --- a/src/main/java/net/dasigns/simpleslots/WeightedRandomGenerator.java +++ b/src/main/java/net/dasigns/simpleslots/WeightedRandomGenerator.java @@ -4,7 +4,7 @@ import java.util.Random; public class WeightedRandomGenerator { - private Random r = new Random(); + private static Random r = new Random(); private ArrayList selection = new ArrayList(); private ArrayList weight = new ArrayList(); @@ -19,15 +19,34 @@ public WeightedRandomGenerator() { public void add(Object item, Integer weight) { this.selection.add(item); this.weight.add(weight); - if(this.weightsum.size() == 0) this.weightsum.add(weight); - else this.weightsum.add(this.weightsum.get(this.weightsum.size()-1) + weight); + + if(this.weightsum.size() == 0) { + this.weightsum.add(weight); + } else { + this.weightsum.add(this.weightsum.get(this.weightsum.size()-1) + weight); + } } public Object next() { - if(this.selection.size() == 0 || this.weight.size() == 0 || this.weightsum.size() == 0) return null; - Integer j = r.nextInt(this.weightsum.get(this.weightsum.size()-1)); - Integer i; - for(i = 0; j > this.weightsum.get(i); i++); + if(this.selection.size() == 0) { + return null; + } + + if(this.weight.size() == 0) { + return null; + } + + if(this.weightsum.size() == 0) { + return null; + } + + + int i = 0; + int j = r.nextInt(this.weightsum.get(this.weightsum.size()-1)); + while{j > this.weightsum.get(i)}{ + i++; + } + return this.selection.get(i); }