fork(2) download
  1. #include <algorithm>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. template<typename Vector>
  6. std::vector<double> rank(const Vector& v)
  7. {
  8. std::vector<std::size_t> w(v.size());
  9. std::iota(begin(w), end(w), 0);
  10. std::sort(begin(w), end(w),
  11. [&v](std::size_t i, std::size_t j) { return v[i] < v[j]; });
  12.  
  13. std::vector<double> r(w.size());
  14. for (std::size_t n, i = 0; i < w.size(); i += n)
  15. {
  16. n = 1;
  17. while (i + n < w.size() && v[w[i]] == v[w[i+n]]) ++n;
  18. for (std::size_t k = 0; k < n; ++k)
  19. {
  20. r[w[i+k]] = i + (n + 1) / 2.0; // average rank of n tied values
  21. // r[w[i+k]] = i + 1; // min
  22. // r[w[i+k]] = i + n; // max
  23. // r[w[i+k]] = i + k + 1; // random order
  24. }
  25. }
  26. return r;
  27. }
  28.  
  29. int main()
  30. {
  31. std::vector<int> v = { 7, 3, 1, 3, 5 };
  32. std::vector<double> ranks = rank(v);
  33.  
  34. for (std::size_t i = 0; i < v.size(); ++i)
  35. std::cout << v[i] << " : " << ranks[i] << '\n';
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
7 : 5
3 : 2.5
1 : 1
3 : 2.5
5 : 4