fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <array>
  7. #include <iterator>
  8.  
  9.  
  10. int main(int, char*[]){
  11. using namespace std;
  12. srand(time(0));
  13.  
  14. // setup bins
  15. int total = 3;
  16. const int MAX_BINS = 10;
  17. array<int,MAX_BINS> bins;
  18.  
  19. // determine weighted distribution
  20. array<float,MAX_BINS> weights;
  21. generate(weights.begin(), weights.end(), [](){
  22. return rand()*1.f/RAND_MAX;
  23. });
  24. float weight_sum = accumulate(weights.begin(), weights.end(), 0.f);
  25.  
  26. // determine portions
  27. // use "extra" to accumulate fractional
  28. float extra = 0;
  29. int used = 0;
  30. for ( int idx = 0; idx < MAX_BINS; ++idx ) {
  31. float actual = weights[idx]/weight_sum * total + extra;
  32. int count = (int)actual;
  33.  
  34. extra = fmodf(actual, 1.f);
  35. bins[idx] = count;
  36. used += count;
  37. }
  38.  
  39. // any accumulation error is added to the first bin
  40. int error = error;
  41. bins[0] += total - used;
  42.  
  43. // output results
  44. cout << "total:\t" << total
  45. << "\nbins:\t";
  46.  
  47. copy(bins.begin(), bins.end(), ostream_iterator<int>(cout, "\t"));
  48. cout << "\nerror:" << error
  49. << "\nextra:" << total - accumulate(bins.begin(),bins.end(),0) << '\n';
  50. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
total:	3
bins:	0	0	0	1	0	1	0	0	0	1	
error:0
extra:0