advent-of-code

advent of code (partial solutions)
Log | Files | Refs | README

commit 205f94488eb8d924f834fbc98bbdfe56f5508921
parent 4d9ab89736f7ad36a1441a9948bd96fa78ccf40d
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Thu,  9 Dec 2021 22:49:25 -0800

silly day 10

Diffstat:
A2021/aoc10.rs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 77 insertions(+), 0 deletions(-)

diff --git a/2021/aoc10.rs b/2021/aoc10.rs @@ -0,0 +1,77 @@ +use std::collections::HashSet; +use std::error::Error; +use std::io::{self, Read}; + +// ascii differences +// ( ) -> 40, 41 prime +// [ ] -> 91, 93 = 3 * 31 +// { } -> 123, 125 = 5 * 25 +// < > -> 60, 62 = 2 * 31 +// +// reads 1 byte at a time, no buffer + +const diffs: [i32; 4] = [3, 19, 21, 21]; + +fn bracket_to_score2(r: u8) -> i64 { + return match r { + 40 => 1, + 91 => 2, + 123 => 3, + 60 => 4, + _ => 0, + }; +} +fn bracket_to_score(r: u8) -> i32 { + let n = match r { + // TODO improve ascii math + 41 => 1, + 93 => 2, + 125 => 3, + 62 => 4, + _ => 0, + }; + let mut t = 1; + for i in 0..n { + t *= diffs[i] + } + return t; +} + +fn main() -> Result<(), Box<dyn Error>> { + let mut stack = vec![]; + let mut skip = false; + let mut part1 = 0; + let mut part2 = vec![]; + for byte in io::stdin().bytes() { + let b = byte.unwrap(); + if b == 15 || b == 10 { + if !skip { + // last line was incomplete, not malformed + part2.push(stack.iter().rev().fold(0i64, |total, val| { + return total * 5 + bracket_to_score2(*val); + })); + } + stack = vec![]; + skip = false; + continue; + } + if skip { + continue; + } + if b != 41 && b % 16 < 13 { + // left bracket + stack.push(b); + } else { + let c = stack.pop().unwrap(); + if !(b > c && b - c <= 2) { + skip = true; + part1 += bracket_to_score(b); + continue; + } + } + } + println!("{}", part1); + part2.sort(); + println!("{}", part2[part2.len() / 2]); + Ok(()) +}