Adding Day 2 solution.
This commit is contained in:
parent
bace232896
commit
f9413dd68d
|
@ -0,0 +1 @@
|
|||
1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,19,9,23,1,23,6,27,1,9,27,31,1,31,10,35,2,13,35,39,1,39,10,43,1,43,9,47,1,47,13,51,1,51,13,55,2,55,6,59,1,59,5,63,2,10,63,67,1,67,9,71,1,71,13,75,1,6,75,79,1,10,79,83,2,9,83,87,1,87,5,91,2,91,9,95,1,6,95,99,1,99,5,103,2,103,10,107,1,107,6,111,2,9,111,115,2,9,115,119,2,13,119,123,1,123,9,127,1,5,127,131,1,131,2,135,1,135,6,0,99,2,0,14,0
|
|
@ -0,0 +1,75 @@
|
|||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
int run_program(std::vector<int> program, int noun, int verb)
|
||||
{
|
||||
int program_counter = 0;
|
||||
bool running = true;
|
||||
program[1] = noun;
|
||||
program[2] = verb;
|
||||
while (running)
|
||||
{
|
||||
auto opcode = program[program_counter++];
|
||||
auto val1 = program[program[program_counter++]];
|
||||
auto val2 = program[program[program_counter++]];
|
||||
|
||||
switch (opcode)
|
||||
{
|
||||
case 1: // addition
|
||||
program[program[program_counter++]] = val1 + val2;
|
||||
break;
|
||||
case 2: // multiplication
|
||||
program[program[program_counter++]] = val1 * val2;
|
||||
break;
|
||||
case 99: // halt
|
||||
default: // unhandled
|
||||
running = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return program[0];
|
||||
}
|
||||
|
||||
int search_program(std::vector<int> program, int expected_value)
|
||||
{
|
||||
for (auto noun = 0; noun < 99; noun++)
|
||||
{
|
||||
for (auto verb = 0; verb < 99; verb++)
|
||||
{
|
||||
auto value = run_program(program, noun, verb);
|
||||
if (value == expected_value)
|
||||
{
|
||||
return 100 * noun + verb;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
std::string line;
|
||||
std::ifstream input_file("../input/day2.txt");
|
||||
std::vector<int> program;
|
||||
|
||||
if (input_file.is_open())
|
||||
{
|
||||
while (getline(input_file, line, ','))
|
||||
{
|
||||
program.push_back(std::stoi(line));
|
||||
}
|
||||
|
||||
auto result1 = run_program(program, 12, 2);
|
||||
std::cout << "Part 1 Result: " << result1 << std::endl;
|
||||
|
||||
auto result2 = search_program(program, 19690720);
|
||||
std::cout << "Part 2 Result: " << result2 << std::endl;
|
||||
|
||||
input_file.close();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue