Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function getRandomWeightedElement(array $weightedValues) {
- $rand = mt_rand(1, (int) array_sum($weightedValues));
- foreach ($weightedValues as $key => $value) {
- $rand -= $value;
- if ($rand <= 0) {
- return $key;
- }
- }
- }
- ?>
- #getRandomWeightedElement
- #Takes in a keyed dictionary and returns a random element
- import random
- def getRandomWeightedElement(**data):
- rand = random.randint(1, sum(data.values()))
- for key, value in data.items():
- rand -= value
- if rand <= 0:
- print(key)
- test1 = {'One':25,'Two':25,'Three':25,'Four':25}
- getRandomWeightedElement(**test1)
Add Comment
Please, Sign In to add comment