Created
September 15, 2020 14:11
-
-
Save apoorvam/949246327d3077efb8480f0913bbdf11 to your computer and use it in GitHub Desktop.
Choose random number of elements from collection with weights
This file contains hidden or 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.Collections; | |
| import java.util.List; | |
| import java.util.Arrays; | |
| import java.util.NavigableMap; | |
| import java.util.Random; | |
| import java.util.TreeMap; | |
| public class WeightedCollection { | |
| private NavigableMap<Integer, String> map = new TreeMap<Integer, String>(); | |
| private Random random; | |
| private int total = 0; | |
| private boolean optional = false; | |
| public WeightedCollection() { | |
| this(new Random()); | |
| } | |
| public WeightedCollection(Random random) { | |
| this.random = random; | |
| } | |
| public void add(int weight, String object) { | |
| if (weight <= 0) return; | |
| total += weight; | |
| map.put(total, object); | |
| } | |
| public void setOptional(boolean optional) { | |
| this.optional = optional; | |
| } | |
| public String getRandomItems() { | |
| int requiredSize = random.nextInt(map.size()) + 1; | |
| if (this.optional && random.nextInt(10) == 0) return ""; | |
| HashSet<String> values = new HashSet<String>(); | |
| while(values.size() < requiredSize) { | |
| int value = random.nextInt(total) + 1; | |
| values.add(map.ceilingEntry(value).getValue()); | |
| } | |
| return String.join(",", values); | |
| } | |
| } | |
| WeightedCollection diseaseStatusCollection = new WeightedCollection(); | |
| diseaseStatusCollection.add(10, 'CONTACT'); | |
| diseaseStatusCollection.add(80, 'CONFIRMED'); | |
| diseaseStatusCollection.add(10, 'SUSPECT'); | |
| System.out.println("reportDiseaseStatus: "+ diseaseStatusCollection.getRandomItems()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment