Guest User

Untitled

a guest
Jul 17th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. <?php
  2. function getRandomWeightedElement(array $weightedValues) {
  3. $rand = mt_rand(1, (int) array_sum($weightedValues));
  4.  
  5. foreach ($weightedValues as $key => $value) {
  6. $rand -= $value;
  7. if ($rand <= 0) {
  8. return $key;
  9. }
  10. }
  11. }
  12. ?>
  13.  
  14. #getRandomWeightedElement
  15. #Takes in a keyed dictionary and returns a random element
  16. import random
  17.  
  18. def getRandomWeightedElement(**data):
  19. rand = random.randint(1, sum(data.values()))
  20.  
  21. for key, value in data.items():
  22. rand -= value
  23. if rand <= 0:
  24. print(key)
  25.  
  26. test1 = {'One':25,'Two':25,'Three':25,'Four':25}
  27.  
  28. getRandomWeightedElement(**test1)
Add Comment
Please, Sign In to add comment