Weighted Random Selection TreeMap
Build cumulative weight bands on a TreeMap and hit them with ceilingEntry, so a random roll lands in the band its weight deserves.
Code
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
public class WeightedPicker {
// 加权随机选择(weighted):把权重累加成区间上界,roll 落进哪段就选谁
record Weighted<T>(T item, double weight) {}
static <T> T pick(List<Weighted<T>> options, double roll) {
NavigableMap<Double, T> bands = new TreeMap<>();
double cumulative = 0;
for (Weighted<T> option : options) {
cumulative += option.weight();
bands.put(cumulative, option.item());
}
return bands.ceilingEntry(roll).getValue();
}
public static void main(String[] args) {
List<Weighted<String>> options = List.of(
new Weighted<>("bronze", 6),
new Weighted<>("silver", 3),
new Weighted<>("gold", 1));
// 总权重 10:roll ∈ [0,6] → bronze,(6,9] → silver,(9,10] → gold
double[] probes = {0, 5.99, 6.01, 8.99, 9.01};
for (double probe : probes) {
System.out.println("roll " + probe + " -> " + pick(options, probe));
}
}
}How the pieces connect
Weighted Random Selection TreeMap keeps everything in the classes WeightedPicker and Weighted and the functions pick and main.
One loop does the cycling here: for (Weighted<T> option : options).
Caveats
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Applying it
The one signature to know: static <T> T pick(List<Weighted<T>> options, double roll)
The run emits 1 labeled section — roll — one per step.
The demo flow inside main is pick — run the file to see it end to end.
Statements that matter
return bands.ceilingEntry(roll).getValue();
cumulative += option.weight();
Interactive Tools for This Topic
Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.Password GeneratorGenerate random passwords from selectable character classes using crypto.getRandomValues with rejection sampling and class guarantees.UUID v4 GeneratorGenerate cryptographically random UUIDs version 4 using the Web Crypto API. Produce single or batch UUIDs with optional uppercase formatting and copy-to-clipboard support.
FAQ
- What does Weighted Random Selection TreeMap print when run?
- Execute the whole file; each printed line is prefixed with a label like `roll`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.