diff --git a/2022/2/main.cpp b/2022/2/main.cpp new file mode 100644 index 0000000..4ebabe4 --- /dev/null +++ b/2022/2/main.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +enum RPS { + Rock = 1, + Paper, + Scissors, +}; + +RPS ToRPS(char c) +{ + if(c == 'A' || c == 'X') + return RPS::Rock; + else if(c == 'B' || c == 'Y') + return RPS::Paper; + else if(c == 'C' || c == 'Z') + return RPS::Scissors; + + std::cerr << "BAD DATA '" << c << "'." << std::endl; + exit(-1); +} + +int RPSScore(RPS rps) +{ + switch(rps) + { + case RPS::Rock: + return 1; + case RPS::Paper: + return 2; + case RPS::Scissors: + return 3; + } +} + +bool Won(RPS us, RPS them) +{ + if(us == RPS::Rock && them == RPS::Scissors) + return true; + else if(us == RPS::Paper && them == RPS::Rock) + return true; + else if(us == RPS::Scissors && them == RPS::Paper) + return true; + + return false; +} + +int Points(RPS us, RPS them) +{ + int rtn = 0; + + // score our play: + rtn += RPSScore(us); + + // tie: + if(us == them) + return rtn + 3; + // win: + if(Won(us, them)) + return rtn + 6; + // loss: + return rtn; +} + +int main() +{ + std::ifstream ifs("data.txt"); + if(!ifs.is_open()) + { + std::cerr << "Missing data.txt." << std::endl; + return -1; + } + + unsigned long total = 0; + + for(std::string line; std::getline(ifs, line); ) + { + char them = line[0]; + char us = line[2]; + + total += Points(ToRPS(us), ToRPS(them)); + } + + std::cout << "Total: " << total << std::endl; + + return 0; +}