2021 Day 2 done in Rust

Code is currently fairly ugly, will try to refactor in a more functional fashion
This commit is contained in:
Teo-CD 2021-12-04 01:18:16 +00:00
parent 218321e6ae
commit 57bf7b2194
4 changed files with 1057 additions and 0 deletions

1000
2021/Day 2/input.txt Normal file

File diff suppressed because it is too large Load diff

5
2021/Day 2/rust_solution/Cargo.lock generated Normal file
View file

@ -0,0 +1,5 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "rust_solution"
version = "0.1.0"

View file

@ -0,0 +1,9 @@
[package]
name = "rust_solution"
version = "0.1.0"
authors = ["Teo-CD"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

View file

@ -0,0 +1,43 @@
use std::fs;
fn first_puzzle(input: &String) {
let mut position = [0; 2];
for line in input.lines() {
if line.contains("forward") {
// Surely there is a better way to parse a string for an integer ?
position[0] += line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
} else if line.contains("up") {
position[1] -= line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
} else if line.contains("down") {
position[1] += line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
}
}
println!("Position : {}, {}", position[0], position[1]);
println!("Multiplied : {}", position[0] * position[1]);
}
fn second_puzzle(input: &String) {
let mut position = [0; 3];
for line in input.lines() {
if line.contains("forward") {
let forward_move = line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
position[0] += forward_move;
position[1] += forward_move * position[2];
} else if line.contains("up") {
position[2] -= line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
} else if line.contains("down") {
position[2] += line.rsplit(' ').next().unwrap().parse::<i32>().unwrap();
}
}
println!("Position : {}, {}", position[0], position[1]);
println!("Multiplied : {}", position[0] * position[1]);
}
fn main() {
let contents = fs::read_to_string("../input.txt").expect("Could not open file.");
first_puzzle(&contents);
second_puzzle(&contents);
0;
}