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); 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); long Report(const long &cycle, const long &x);
void ApplyAction(const std::pair<Command, std::string> &command, long &x); void ApplyAction(const std::pair<Command, std::string> &command, long &x);
@ -57,7 +58,7 @@ int main()
for(const auto &command : commands) for(const auto &command : commands)
{ {
// Step 1: Increase cycle count of command to see if we would have reported // 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: // Step 2: Report, if needed:
total += Report(cycle, x); total += Report(cycle, x);
@ -68,7 +69,7 @@ int main()
while(cycle <= 220) while(cycle <= 220)
{ {
IncrementCycleCount(cycle, Command::NOOP); StepCycles(cycle, Command::NOOP, x);
total += Report(cycle, x); total += Report(cycle, x);
} }
@ -80,15 +81,16 @@ int main()
return 0; return 0;
} }
void IncrementCycleCount(long &cycle, const Command &command) void StepCycles(long &cycle, const Command &command, const long &x)
{ {
switch(command) switch(command)
{ {
case Command::NOOP: case Command::NOOP:
cycle++; IncrementAndDraw(x, cycle);
break; break;
case Command::ADDX: case Command::ADDX:
cycle += 2; for(auto i = 0; i < 2; ++i)
IncrementAndDraw(x, cycle);
break; break;
default: default:
std::cerr << "Missing ability to parse command type." << std::endl; 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; auto next_cycle = last_reported_cycle + 40;
if(cycle > next_cycle) if(cycle > next_cycle)
{ {
std::cout << "Cycle #" << next_cycle << ": " // std::cout << "Cycle #" << next_cycle << ": "
<< next_cycle << " * " << x << " = " // << next_cycle << " * " << x << " = "
<< next_cycle * x << std::endl; // << next_cycle * x << std::endl;
last_reported_cycle += 40; last_reported_cycle += 40;
return next_cycle * x; return next_cycle * x;
@ -132,3 +134,21 @@ void ApplyAction(const std::pair<Command, std::string> &command, long &x)
break; 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;
}
}