Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- [2016-01-11] Challenge #249 [Easy] Playing the Stock Market
- https://www.reddit.com/r/dailyprogrammer/comments/40h9pd/20160111_challenge_249_easy_playing_the_stock/?sort=top
- */
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <string>
- //Read in the inputFile and return the vector
- std::vector<double> readFile(std::string fileName) {
- std::vector<double> vec;
- std::ifstream inputFile(fileName);
- if (inputFile.is_open()) {
- double val;
- // Read from file until empty
- while (inputFile >> val) {
- vec.push_back(val); // Store in vector only valid values.
- }
- }
- inputFile.close(); // not really needed, would be automagically closed when out of scope.
- return vec;
- }
- int main() {
- std::vector<double> vec = readFile("inputFile.txt");
- if (vec.size() <= 2) {
- std::cout << "Error: unable to load data from inputFile.txt" << std::endl;
- return 1;
- }
- double bestProfit = 0;
- double buy = 0;
- double sell = 0;
- constexpr long delay = 1; // 0 = test next, 1 = test with one tick delay
- // Slow but tests all cases.
- auto last = std::prev(vec.end(), delay); // adjust end point for the look ahead start point
- for (auto buyLoop = vec.begin(); buyLoop != last; ++buyLoop) {
- auto sellLoop = std::next(buyLoop, delay); // adjust starting look-ahead for tick delay
- for (++sellLoop; sellLoop != vec.end(); ++sellLoop) {
- // Check if this buy/sell combo is better then the current best
- double profit = *sellLoop - *buyLoop;
- if (profit > bestProfit) {
- bestProfit = profit;
- buy = *buyLoop;
- sell = *sellLoop;
- }
- }
- }
- std::cout << "buy sell profit : " << buy << " " << sell << " " << bestProfit << std::endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment