1package com.fs.starfarer.api.util;
3import java.util.ArrayList;
4import java.util.Collection;
5import java.util.Collections;
6import java.util.Comparator;
7import java.util.HashMap;
10import java.util.Random;
12import org.json.JSONArray;
13import org.json.JSONException;
15import com.fs.starfarer.api.campaign.econ.MarketAPI;
35 private float total = 0f;
36 private final boolean ignoreWeights;
38 private Random random =
null;
45 this.ignoreWeights = ignoreWeights;
58 for (
int i = 0; i <
arr.length(); i++) {
59 weights.
add((
float)
arr.getDouble(i));
62 }
catch (JSONException e) {
63 throw new RuntimeException(e);
68 Object writeReplace() {
69 JSONArray arr =
new JSONArray();
70 for (Float f : weights) {
92 for (
T item : items) {
98 for (
int i = 0; i < other.items.size(); i++) {
99 add(other.items.get(i), other.weights.get(i));
106 public void add(
T item,
float weight) {
108 if (weight <= 0)
return;
114 public void remove(
T item) {
115 int index = items.indexOf(item);
118 float weight = weights.
remove(index);
124 return items.isEmpty();
132 int index = items.indexOf(item);
133 if (index < 0)
return 0;
138 return weights.get(index);
142 weights.set(index, weight);
153 Random orig = this.random;
154 this.random = random;
161 if (items.isEmpty())
return null;
165 if (random !=
null) {
166 index = (
int) (random.nextDouble() * items.size());
168 index = (
int) (
Math.random() * items.size());
170 return items.get(index);
174 if (this.random !=
null) {
175 random = this.random.nextFloat() * total;
177 random = (
float) (
Math.random() * total);
179 if (random > total) random = total;
184 for (
Float weight : weights) {
189 return items.get(
Math.min(index, items.size() - 1));
197 this.random = random;
203 System.out.println(title);
206 for (
int i = 0; i < items.size(); i++) {
207 T item = items.get(i);
214 return o1.toString().compareTo(
o2.toString());
220 float weight = weights.get(index);
222 String percent =
"" + (
int)((weight / total) * 100f) +
"%";
227 itemStr = ((MarketAPI)item).getName();
static String getRoundedValue(float value)
void add(T item, float time)
WeightedRandomPicker(Random random)
void addAll(Collection< T > items)
WeightedRandomPicker< T > clone()
void addAll(WeightedRandomPicker< T > other)
void setWeight(int index, float weight)
void setRandom(Random random)
WeightedRandomPicker(boolean ignoreWeights)
float getWeight(int index)
void add(T item, float weight)