Skip to content

Instantly share code, notes, and snippets.

@DynamicField
Created January 8, 2018 19:39
Show Gist options
  • Save DynamicField/fb2eb4bcfe05cd3b246d1e986a83abec to your computer and use it in GitHub Desktop.
Save DynamicField/fb2eb4bcfe05cd3b246d1e986a83abec to your computer and use it in GitHub Desktop.
Randomchooser
package com.jeuxjeux20.tools.random;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* <p>An {@link HashMap} to get random values followed by its chance to get it. </p>
* <h5>For example : </h5>
* <p>We will initialize it with the type {@link String}.</p>
* <code>RandomChooser&lt;String&gt; myChooser = new RandomChooser<>();</code>
* <p> We will add two items to it. </p>
* <code>myChooser.Put("Android",2); <br> myChooser.Put("iOS", 1);</code>
* <p>For Android, there is a chance of <b>2</b>, and iOS, <b>1</b>.
* Which means that there is 2/3 chance for Android to be chosen, and 1/3 chance for iOS to be chosen.</p>
* <p>Now, let's see what goes out of the box !</p>
* <code>System.out.println(myChooser.GetRandomItem());<br>> Android</code>
* <p>Well, looks like Android got there. After all, he had 2/3 chances to be chosen. So not much luck !</p>
* @author jeuxjeux20
*
* @param <T> The used type in the collection
*/
public class RandomChooser<T> extends HashMap<T, Integer>{
private static final long serialVersionUID = 1L;
private Random Randomiser = new Random();
/**
* Gives a random item following the chances given by the {@link Integer} values.
* @throws InvalidAlgorithmParameterException When there are no items.
*/
public T GetRandomItem() throws InvalidAlgorithmParameterException {
if (this.size() <= 0) throw new InvalidAlgorithmParameterException("No items");
int sum = 0;
for(int chance : this.values()) {
sum += chance;
}
int randomValue = Randomiser.nextInt(sum);
int i = 0;
for (Map.Entry<T, Integer> thing : this.entrySet()) {
if (randomValue < thing.getValue() + i) {
return thing.getKey();
}
else {
i += thing.getValue();
}
}
throw new InvalidAlgorithmParameterException("idk");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment