Deserializes a string to create a WeightedRandom @param str The string serialized using WeightedRandom#toString(Function) @param converter A function to convert the serialized outcomes back to objects @param The type of the outcomes @return The deserialized WeightedRandom
(String str, Function<String, T> converter)
| 225 | * @return The deserialized WeightedRandom |
| 226 | */ |
| 227 | public static <T> WeightedRandom<T> fromString(String str, Function<String, T> converter) { |
| 228 | JSONList list = JSONParser.parseList(str); |
| 229 | Map<T, Double> map = new HashMap<>(); |
| 230 | for (int i = 0; i < list.size(); i++) { |
| 231 | JSONMap entry = list.getMap(i); |
| 232 | T outcome = converter.apply(entry.getString("outcome")); |
| 233 | double weight = entry.getDouble("weight"); |
| 234 | map.put(outcome, weight); |
| 235 | } |
| 236 | return fromDoubleMap(map); |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Performs a single roll given a map of outcomes to weights. If you need to roll multiple times, instantiate a WeightedRandom and call roll on that each time instead. |