fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <random> //For std::mt19937, std::random_device(), and std::uniform_int_distribution()
  4. #include <algorithm> //For std::shuffle
  5.  
  6. void FillBuckets(std::vector<int> &buckets, const int amountToDistribute)
  7. {
  8. std::mt19937 randomGenerator(std::random_device{}());
  9.  
  10. //We generate some indices to fill the bucket elements in a random order.
  11. std::vector<size_t> bucketIndices(buckets.size());
  12. std::iota(begin(bucketIndices), end(bucketIndices), 0);
  13. std::shuffle(begin(bucketIndices), end(bucketIndices), randomGenerator);
  14.  
  15. int bucketsRemaining = static_cast<int>(bucketIndices.size());
  16. int amountRemaining = amountToDistribute;
  17.  
  18. for(size_t index : bucketIndices)
  19. {
  20. int amountToGive = 0;
  21.  
  22. //If this isn't the last bucket, take a random amount of the remaining value.
  23. if(bucketsRemaining > 1)
  24. {
  25. //Balances out the numbers a bit more, so the first few buckets don't steal everything.
  26. //This means, if there are two buckets remaining, one of the buckets can take 100%.
  27. //If there are three buckets remaining, the most each bucket can take is 50%.
  28. //If there are four buckets remaining, the most each bucket can take is 33%, and so on.
  29. int maxToGive = (amountRemaining / (bucketsRemaining-1));
  30. amountToGive = std::uniform_int_distribution<int>(0, maxToGive)(randomGenerator);
  31. }
  32. //If this IS the last bucket, just take everything that remains.
  33. else
  34. {
  35. amountToGive = amountRemaining;
  36. }
  37.  
  38. buckets[index] = amountToGive;
  39. amountRemaining -= amountToGive;
  40.  
  41. bucketsRemaining--;
  42. }
  43. }
  44.  
  45. int main()
  46. {
  47. std::vector<int> buckets(10);
  48. FillBuckets(buckets, 100);
  49.  
  50. std::cout << "Result: ";
  51. for(int amount : buckets)
  52. {
  53. std::cout << amount << " ";
  54. }
  55. std::cout << std::endl;
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Result: 3 39 10 10 16 5 2 7 8 0