DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 2: 1202 Program Alarm

Collapse
 
noakpalander profile image
Noak Palander • Edited

A bit late to the party, got my c++17 code working however

#include <fstream>
#include <vector>
#include <string>
#include <optional>
#include <optional>
#include <iostream>
#include <cmath>
#include <sstream>

std::optional<std::vector<unsigned int>> ReadFile(const std::string& filename) {
std::ifstream reader(filename.c_str());

    if (reader) {
        std::string data;
        reader >> data;

        std::stringstream ss(data);

        std::vector<unsigned int> out;
        for (unsigned int val; ss >> val;) {
            out.emplace_back(val);
            if (ss.peek() == ',')
                ss.ignore();
        }

        return out;
    }

    return {};
}

unsigned int Calculate(unsigned int first, unsigned int second, std::vector<unsigned int> data) {
    // Set initial values
    data[1] = first;
    data[2] = second;

    for (unsigned int i = 0; i < data.size(); i += 4) {
        const unsigned int FIRST = data[i + 1];
        const unsigned int SECOND = data[i + 2];
        const unsigned int LOCATION = data[i + 3];


        switch (data[i]) {
            // Addition
            case 1:
                data[LOCATION] = data[FIRST] + data[SECOND];
                break;

            // Multiplication
            case 2:
                data[LOCATION] = data[FIRST] * data[SECOND];
                break;

            // Terminate
            case 99:
                return data[0];
                break;

            default:
                break;
        }
    }

    return data[0];
}


int main() {
    if (auto data = ReadFile("puzzle_input"); data.has_value()) {
        /* Part one */
        unsigned int ans1 = Calculate(12, 2, data.value());
        std::cout << "The answer to part_1 is " << ans1 << "\n";

        /* Part 2 */
        // Reset data set
        data.value() = ReadFile("puzzle_input").value();

        const unsigned int GOAL = 19690720;

        // 100*100 is enough iterations
        for (unsigned int noun = 0; noun < 100; noun++)
            for (unsigned int verb = 0; verb < 100; verb++)
                if (Calculate(noun, verb, data.value()) == GOAL)
                    std::cout << "\nThe answer to part_2 is " << 100 * noun + verb << "\n";
    }
    else
        std::cerr << "Failed to read puzzle_input!\n";

    return 0;
}