Refactored a bit to get the answer for part 2, day 10.

This commit is contained in:
David Vereb 2022-12-20 15:30:39 -05:00
parent 37c1fb045f
commit f80787cadb

View File

@ -23,7 +23,8 @@ Command ParseCommand(const std::string &str) {
exit(-1);
}
void IncrementCycleCount(long &cycle, const Command &command);
void StepCycles(long &cycle, const Command &command, const long &x);
void IncrementAndDraw(const long &x, long &cycle);
long Report(const long &cycle, const long &x);
void ApplyAction(const std::pair<Command, std::string> &command, long &x);
@ -57,7 +58,7 @@ int main()
for(const auto &command : commands)
{
// Step 1: Increase cycle count of command to see if we would have reported
IncrementCycleCount(cycle, command.first);
StepCycles(cycle, command.first, x);
// Step 2: Report, if needed:
total += Report(cycle, x);
@ -68,7 +69,7 @@ int main()
while(cycle <= 220)
{
IncrementCycleCount(cycle, Command::NOOP);
StepCycles(cycle, Command::NOOP, x);
total += Report(cycle, x);
}
@ -80,15 +81,16 @@ int main()
return 0;
}
void IncrementCycleCount(long &cycle, const Command &command)
void StepCycles(long &cycle, const Command &command, const long &x)
{
switch(command)
{
case Command::NOOP:
cycle++;
IncrementAndDraw(x, cycle);
break;
case Command::ADDX:
cycle += 2;
for(auto i = 0; i < 2; ++i)
IncrementAndDraw(x, cycle);
break;
default:
std::cerr << "Missing ability to parse command type." << std::endl;
@ -103,9 +105,9 @@ long Report(const long &cycle, const long &x)
auto next_cycle = last_reported_cycle + 40;
if(cycle > next_cycle)
{
std::cout << "Cycle #" << next_cycle << ": "
<< next_cycle << " * " << x << " = "
<< next_cycle * x << std::endl;
// std::cout << "Cycle #" << next_cycle << ": "
// << next_cycle << " * " << x << " = "
// << next_cycle * x << std::endl;
last_reported_cycle += 40;
return next_cycle * x;
@ -132,3 +134,21 @@ void ApplyAction(const std::pair<Command, std::string> &command, long &x)
break;
};
}
void IncrementAndDraw(const long &x, long &cycle)
{
static int drawing_index = 1; // 1 to 40
// NOTE(dev): using -0 and +2 instead of -1 and +1 to account for 0-based vs 1-based
if(drawing_index >= x - 0 && drawing_index <= x + 2) // within one or on target
std::cout << "#";
else
std::cout << ".";
++cycle;
if(++drawing_index > 40)
{
std::cout << std::endl;
drawing_index = 1;
}
}