commit c70021f79022a907ac687d7ea5ee8ec4705413e9
parent dcac2c32d51762c729f68004e2c021c4617f81bc
Author: Shimmy Xu <shimmy.xu@shimmy1996.com>
Date: Mon, 2 Dec 2019 00:40:22 -0500
Add Rust solution for day 2
Diffstat:
2 files changed, 65 insertions(+), 0 deletions(-)
diff --git a/day-02/Makefile b/day-02/Makefile
@@ -0,0 +1,13 @@
+CC := g++
+CCFLAGS := --std=c++17 -Wall
+
+all: day-02-cpp day-02-rust day-02.jl
+ julia day-02.jl
+ ./day-02-cpp
+ ./day-02-rust
+
+day-02-cpp: day-02.cc
+ $(CC) $(CCFLAGS) $^ -o $@
+
+day-02-rust: day-02.rs
+ rustc $^ -o $@
diff --git a/day-02/day-02.rs b/day-02/day-02.rs
@@ -0,0 +1,52 @@
+fn main() {
+ let input = std::fs::read_to_string("input.txt")
+ .unwrap()
+ .trim()
+ .split(",")
+ .map(|op| op.parse::<usize>().unwrap())
+ .collect::<Vec<usize>>();
+ println!("Rust:");
+ println!("Part 1: {}", part_1(&input));
+ println!("Part 2: {}", part_2(&input));
+}
+
+fn computer(input: &Vec<usize>, noun: usize, verb: usize) -> usize {
+ let mut input: Vec<usize> = input.clone();
+ input[1] = noun;
+ input[2] = verb;
+
+ let mut pc = 0;
+ loop {
+ match input[pc] {
+ 1 => {
+ let res_loc = input[pc + 3];
+ input[res_loc] = input[input[pc + 1]] + input[input[pc + 2]];
+ pc += 4;
+ }
+ 2 => {
+ let res_loc = input[pc + 3];
+ input[res_loc] = input[input[pc + 1]] * input[input[pc + 2]];
+ pc += 4;
+ }
+ 99 => break,
+ _ => {}
+ }
+ }
+
+ input[0]
+}
+
+fn part_1(input: &Vec<usize>) -> usize {
+ computer(&input, 12, 2)
+}
+
+fn part_2(input: &Vec<usize>) -> usize {
+ for noun in 0..=99 {
+ for verb in 0..=99 {
+ if computer(&input, noun, verb) == 19690720 {
+ return noun * 100 + verb;
+ }
+ }
+ }
+ 0
+}