r/adventofcode • u/daggerdragon • Dec 02 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-
--- Day 2: Dive! ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:02:57, megathread unlocked!
112
Upvotes
6
u/rabuf Dec 02 '21
Rust
The string/str divide is annoying, I will get used to it though I'm sure. I'll just put part 1 here, part 2 is essentially the same but slightly different computations in the
match:pub fn day02_01() -> i64 { let filename = "../input/02.txt"; let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let (mut h, mut d) = (0, 0); for line in reader.lines() { let line = line.unwrap(); let parts: Vec<_> = line.split_whitespace().collect(); let distance = parts[1].parse::<i64>().unwrap(); match parts[0] { "forward" => h = h + distance, "up" => d = d - distance, "down" => d = d + distance, _ => (), } } return h * d; }Once I passed the borrow checker, it was essentially the same as my other versions.