fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <queue>
  5. #include <string>
  6.  
  7. std::vector<int> data = {10, 6, 3, 8, 2, 5};
  8. std::vector<float> test = {10, 8, 4.5, 5.5, 5, 3.5};
  9. std::vector<float> result;
  10.  
  11. const int avg = 2; // rolling average of two
  12.  
  13. /* Use a queue to keep the history and another integer for current sum */
  14. /* Check the queue size before use. */
  15. void rolling_avg(int &next) {
  16. static int sum = 0;
  17. static std::queue<int> pool;
  18.  
  19. if(pool.size() != avg) {
  20. // pool is not full yet. Add to sum and push in queue.
  21. sum += next;
  22. pool.push(next);
  23. } else {
  24. // pool is full. Remove the first from sum and add the next data.
  25. sum -= pool.front();
  26. pool.pop();
  27.  
  28. sum += next;
  29. pool.push(next);
  30. }
  31.  
  32. result.push_back((float)sum / pool.size());
  33. }
  34.  
  35.  
  36. void read_dat_and_process(const std::string &filepath) {
  37. std::cout << "reading file: " << filepath << std::endl;
  38.  
  39. // Read line by line and get the second token.
  40. // Ignore some data cleaning in this method for demo only.
  41. // And ignore proper error handling.
  42. std::ifstream infile(filepath);
  43. int line_num = 0, num = 0;
  44.  
  45. std::cout << "...start processing" << std::endl;
  46. while(infile >> line_num >> num) {
  47. std::cout << line_num << " " << num << std::endl;
  48. /* for every num, run the rolling_avg function to populate the result vector.*/
  49. rolling_avg(num);
  50. }
  51. std::cout << "...end of file" << std::endl;
  52.  
  53. infile.close();
  54. }
  55.  
  56. int main() {
  57.  
  58. read_dat_and_process("read_avg_test.dat");
  59.  
  60. std::cout << "result: ";
  61. for(auto num : result)
  62. std::cout << num << " ";
  63. std::cout << std::endl;
  64.  
  65.  
  66. /* Sample code for using the method: rolling_avg */
  67.  
  68. // for(auto num : data)
  69. // rolling_avg(num);
  70.  
  71. // std::cout << "data: ";
  72. // for(auto num : data)
  73. // std::cout << num << " ";
  74. // std::cout << std::endl;
  75.  
  76. // std::cout << "test: ";
  77. // for(auto num : test)
  78. // std::cout << num << " ";
  79. // std::cout << std::endl;
  80.  
  81. // std::cout << "result: ";
  82. // for(auto num : result)
  83. // std::cout << num << " ";
  84. // std::cout << std::endl;
  85.  
  86. return 0;
  87. }
Success #stdin #stdout 0s 4428KB
stdin
Standard input is empty
stdout
reading file: read_avg_test.dat
...start processing
...end of file
result: