Guest User

Challenge #249 [Easy] Playing the Stock Market

a guest
Jan 30th, 2016
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. /*
  2. [2016-01-11] Challenge #249 [Easy] Playing the Stock Market
  3.  
  4. https://www.reddit.com/r/dailyprogrammer/comments/40h9pd/20160111_challenge_249_easy_playing_the_stock/?sort=top
  5. */
  6. #include <iostream>
  7. #include <fstream>
  8. #include <vector>
  9. #include <string>
  10.  
  11.  
  12. //Read in the inputFile and return the vector
  13. std::vector<double> readFile(std::string fileName) {
  14.     std::vector<double> vec;
  15.  
  16.     std::ifstream inputFile(fileName);
  17.  
  18.     if (inputFile.is_open()) {
  19.         double val;
  20.         // Read from file until empty
  21.         while (inputFile >> val) {
  22.             vec.push_back(val); // Store in vector only valid values.
  23.         }
  24.     }
  25.  
  26.     inputFile.close(); // not really needed, would be automagically closed when out of scope.
  27.  
  28.     return vec;
  29. }
  30.  
  31.  
  32. int main() {
  33.  
  34.     std::vector<double> vec = readFile("inputFile.txt");
  35.  
  36.     if (vec.size() <= 2) {
  37.         std::cout << "Error: unable to load data from inputFile.txt" << std::endl;
  38.         return 1;
  39.     }
  40.  
  41.     double bestProfit = 0;
  42.     double buy = 0;
  43.     double sell = 0;
  44.     constexpr long delay = 1; // 0 = test next, 1 = test with one tick delay
  45.  
  46.     // Slow but tests all cases.
  47.     auto last = std::prev(vec.end(), delay); // adjust end point for the look ahead start point
  48.     for (auto buyLoop = vec.begin(); buyLoop != last; ++buyLoop) {
  49.  
  50.         auto sellLoop = std::next(buyLoop, delay); // adjust starting look-ahead for tick delay
  51.         for (++sellLoop; sellLoop != vec.end(); ++sellLoop) {
  52.  
  53.             // Check if this buy/sell combo is better then the current best
  54.             double profit = *sellLoop - *buyLoop;
  55.             if (profit > bestProfit) {
  56.                 bestProfit = profit;
  57.                 buy = *buyLoop;
  58.                 sell = *sellLoop;
  59.             }
  60.         }
  61.     }
  62.     std::cout << "buy sell profit : " << buy << " " << sell << " " << bestProfit << std::endl;
  63.  
  64.     return 0;
  65. }
Add Comment
Please, Sign In to add comment