fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. class ProductRating
  8. {
  9. public:
  10. ProductRating(int id): id_(id),up(0),total(0) {}
  11. void add_rating(int stars) { up += stars, total += 5; }
  12. double low_score(double z)const
  13. {
  14. if (!total) return 0;
  15. double n = total;
  16. double p = up/n;
  17. return (p + z*z/(2*n) - z * sqrt((p*(1-p)+z*z/(4*n))/n))/(1+z*z/n);
  18. }
  19. double avg_score()const { return total ? (double)up/total : 0; }
  20. int id()const {return id_;};
  21. private:
  22. int id_;
  23. int up;
  24. int total;
  25. };
  26.  
  27. bool avg_cmp_rev(const ProductRating& a, const ProductRating& b)
  28. {
  29. return b.avg_score() < a.avg_score();
  30. }
  31.  
  32. bool low_cmp_rev(const ProductRating& a, const ProductRating& b)
  33. {
  34. return b.low_score(1.96) < a.low_score(1.96);
  35. }
  36.  
  37. int main()
  38. {
  39. vector<ProductRating> rating_list;
  40. rating_list.push_back(ProductRating(1));
  41. rating_list.push_back(ProductRating(2));
  42. rating_list.push_back(ProductRating(3));
  43.  
  44. // 3 lần đánh giá 5 sao
  45. rating_list[0].add_rating(5);
  46. rating_list[0].add_rating(5);
  47. rating_list[0].add_rating(5);
  48.  
  49. // 100 lần đánh giá 5 sao, 2 lần đánh giá 2 sao
  50. for (int i=0; i<100; ++i) rating_list[1].add_rating(5);
  51. rating_list[1].add_rating(2);
  52. rating_list[1].add_rating(2);
  53.  
  54. // 2 > 1 > 3
  55.  
  56. cout << "Average score:\n";
  57. for (size_t i=0; i<rating_list.size(); ++i)
  58. cout << "Product " << rating_list[i].id() << ": "
  59. << rating_list[i].avg_score() << '\n';
  60.  
  61. cout << "\nLower bound of Wilson score, 95% confidence:\n";
  62. for (size_t i=0; i<rating_list.size(); ++i)
  63. cout << "Product " << rating_list[i].id() << ": "
  64. << rating_list[i].low_score(1.96) << '\n';
  65.  
  66. sort(rating_list.begin(), rating_list.end(), avg_cmp_rev);
  67. cout << "\nAfter sorted by average score: ";
  68. for (size_t i=0; i<rating_list.size(); ++i)
  69. cout << rating_list[i].id() << " ";
  70. cout << "\n";
  71.  
  72. sort(rating_list.begin(), rating_list.end(), low_cmp_rev);
  73. cout << "After sorted by lower bound of Wilson score (95% confidence): ";
  74. for (size_t i=0; i<rating_list.size(); ++i)
  75. cout << rating_list[i].id() << " ";
  76. cout << "\n";
  77. }
  78.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
Average score:
Product 1: 1
Product 2: 0.988235
Product 3: 0

Lower bound of Wilson score, 95% confidence:
Product 1: 0.796111
Product 2: 0.974573
Product 3: 0

After sorted by average score: 1 2 3 
After sorted by lower bound of Wilson score (95% confidence): 2 1 3