Created
March 17, 2014 01:18
-
-
Save sochoa/9592298 to your computer and use it in GitHub Desktop.
Submission for https://www.hackerrank.com/challenges/chocolate-feast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <exception> | |
#include <vector> | |
int main(const int argc, const char** argv) { | |
const int UNSET = -1; | |
const int BEGINNING = 0; | |
const std::string DELIMITER = " "; | |
const size_t NOT_FOUND = std::string::npos; | |
int num_tests = UNSET; | |
size_t pos = BEGINNING; | |
std::vector< std::vector<int> > tests; | |
std::string line; | |
std::string token; | |
for (std::string line; std::getline(std::cin, line);) { | |
if (UNSET == num_tests) { | |
num_tests = atoi(line.c_str()); | |
continue; | |
} | |
std::vector< int > test; | |
// while it is delimited, parse it | |
while ((pos = line.find(DELIMITER)) != NOT_FOUND) { | |
token = line.substr(BEGINNING, pos); | |
test.push_back(atoi(token.c_str())); | |
line.erase(BEGINNING, pos + DELIMITER.length()); | |
} | |
// the last token | |
test.push_back(atoi(line.c_str())); | |
if (test.size() != 3) { | |
std::cout << "Invalid test" << std::endl; | |
test.clear(); | |
continue; | |
} | |
int money = test[0]; | |
int price_per_chocolate = test[1]; | |
int num_wrappers_per_free_piece = test[2]; | |
int num_chocolates = 0; | |
// Invalid | |
if (money <= 0) | |
continue; | |
// Valid, but we're broke | |
if ( (price_per_chocolate <= 0) || | |
(price_per_chocolate > money) ) | |
continue; | |
// Invalid | |
if (num_wrappers_per_free_piece <= 0) | |
continue; | |
while (money >= price_per_chocolate) { | |
money -= price_per_chocolate; | |
num_chocolates++; | |
if (num_chocolates % num_wrappers_per_free_piece == 0) { | |
num_chocolates++; | |
} | |
} | |
std::cout << num_chocolates << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment