commit c8314391d9ee95a5b2697b5dc35b190ddb009a89
parent c70021f79022a907ac687d7ea5ee8ec4705413e9
Author: Shimmy Xu <shimmy.xu@shimmy1996.com>
Date: Mon, 2 Dec 2019 08:50:13 -0500
Add C++ and Julia solutions for day 02
Diffstat:
2 files changed, 89 insertions(+), 0 deletions(-)
diff --git a/day-02/day-02.cc b/day-02/day-02.cc
@@ -0,0 +1,50 @@
+#include <fstream>
+#include <iostream>
+#include <vector>
+
+auto computer(std::vector<int> input, int noun, int verb) {
+ input[1] = noun;
+ input[2] = verb;
+
+ auto pc = 0;
+ while (true) {
+ if (input[pc] == 1) {
+ input[input[pc + 3]] = input[input[pc + 1]] + input[input[pc + 2]];
+ pc += 4;
+ } else if (input[pc] == 2) {
+ input[input[pc + 3]] = input[input[pc + 1]] * input[input[pc + 2]];
+ pc += 4;
+ } else if (input[pc] == 99) {
+ break;
+ }
+ }
+
+ return input[0];
+}
+
+auto part_1(std::vector<int>& input) -> int {
+ return computer(input, 12, 2);
+}
+
+auto part_2(std::vector<int>& input) -> int {
+ for (auto noun = 0; noun <= 99; ++noun) {
+ for (auto verb = 0; verb <= 99; ++verb) {
+ if (computer(input, noun, verb) == 19690720) {
+ return noun * 100 + verb;
+ }
+ }
+ }
+ return 0;
+}
+
+auto main() -> int {
+ auto input_file = std::ifstream("input.txt");
+ auto input = std::vector<int>{};
+ for (std::string op; std::getline(input_file, op, ',');) {
+ input.push_back(std::stoi(op));
+ }
+
+ std::cout << "C++17:\n"
+ << "Part 1: " << part_1(input) << "\nPart 2: " << part_2(input)
+ << std::endl;
+}
diff --git a/day-02/day-02.jl b/day-02/day-02.jl
@@ -0,0 +1,39 @@
+function computer(input, noun, verb)
+ input = copy(input)
+ input[2] = noun
+ input[3] = verb
+ pc = 1
+ while true
+ if input[pc] == 1
+ input[input[pc + 3] + 1] = input[input[pc + 1] + 1] + input[input[pc + 2] + 1]
+ pc += 4
+ elseif input[pc] == 2
+ input[input[pc + 3] + 1] = input[input[pc + 1] + 1] * input[input[pc + 2] + 1]
+ pc += 4
+ elseif input[pc] == 99
+ break
+ end
+ end
+ input[1]
+end
+
+function part_1(input)
+ computer(input, 12, 2)
+end
+
+function part_2(input)
+ for noun = 0:99
+ for verb = 0:99
+ if computer(input, noun, verb) == 19690720
+ return noun * 100 + verb
+ end
+ end
+ end
+ 0
+end
+
+input = map(x -> parse(Int32, x), split(readlines(open("input.txt"))[1], ','))
+
+println("Julia:")
+println("Part 1: ", part_1(input))
+println("Part 2: ", part_2(input))