Advent-of-Code/2022/2/main.cpp

128 lines
2.0 KiB
C++

#include <fstream>
#include <iostream>
#include <string>
enum RPS {
Rock = 1,
Paper,
Scissors,
};
enum Result {
Lose = 1,
Draw,
Win,
};
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;
}
RPS Which(RPS them, Result desired)
{
if(desired == Result::Draw)
return them; // same
switch(them)
{
case RPS::Rock:
if(desired == Result::Lose)
return RPS::Scissors;
return RPS::Paper;
case RPS::Paper:
if(desired == Result::Lose)
return RPS::Rock;
return RPS::Scissors;
case RPS::Scissors:
if(desired == Result::Lose)
return RPS::Paper;
return RPS::Rock;
}
}
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;
unsigned long new_total = 0;
for(std::string line; std::getline(ifs, line); )
{
char them = line[0];
char us = line[2];
Result r = Result::Lose;
if(us == 'Y')
r = Result::Draw;
else if(us == 'Z')
r = Result::Win;
RPS todo = Which(ToRPS(them), r);
total += Points(ToRPS(us), ToRPS(them));
new_total += Points(todo, ToRPS(them));
}
std::cout << " Total: " << total << std::endl;
std::cout << "New Total: " << new_total << std::endl;
return 0;
}