diff options
author | Federico Igne <git@federicoigne.com> | 2021-12-13 14:34:24 +0000 |
---|---|---|
committer | Federico Igne <git@federicoigne.com> | 2021-12-13 14:34:24 +0000 |
commit | 0569bae066cfdd5ed388a60a470c882fa87f0a4c (patch) | |
tree | ae237b130a3c9961322c86f591b5b02fe1b6f9c5 /day10/src | |
parent | e8ad18ed7b9de796208a2a55133c80430add2fb9 (diff) | |
download | aoc-0569bae066cfdd5ed388a60a470c882fa87f0a4c.tar.gz aoc-0569bae066cfdd5ed388a60a470c882fa87f0a4c.zip |
Day 10
Diffstat (limited to 'day10/src')
-rw-r--r-- | day10/src/main.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/day10/src/main.rs b/day10/src/main.rs new file mode 100644 index 0000000..11f1f2c --- /dev/null +++ b/day10/src/main.rs | |||
@@ -0,0 +1,69 @@ | |||
1 | use std::fs; | ||
2 | use std::path::Path; | ||
3 | use std::collections::HashMap; | ||
4 | use lazy_static::lazy_static; | ||
5 | |||
6 | lazy_static! { | ||
7 | static ref SCORE1: HashMap<u8,u32> = { | ||
8 | let mut m = HashMap::new(); | ||
9 | m.insert(b')', 3); | ||
10 | m.insert(b']', 57); | ||
11 | m.insert(b'}', 1197); | ||
12 | m.insert(b'>', 25137); | ||
13 | m | ||
14 | }; | ||
15 | static ref SCORE2: HashMap<u8,u64> = { | ||
16 | let mut m = HashMap::new(); | ||
17 | m.insert(b')', 1); | ||
18 | m.insert(b']', 2); | ||
19 | m.insert(b'}', 3); | ||
20 | m.insert(b'>', 4); | ||
21 | m | ||
22 | }; | ||
23 | } | ||
24 | |||
25 | /* AOC21 Day 10: https://adventofcode.com/2021/day/10 */ | ||
26 | fn main() { | ||
27 | let input = Path::new("resources").join("input.txt"); | ||
28 | let content = fs::read_to_string(input).expect("Unable to read input file"); | ||
29 | ex1(&content); | ||
30 | ex2(&content); | ||
31 | } | ||
32 | |||
33 | fn ex1(content: &str) { | ||
34 | let ex1: u32 = | ||
35 | content.lines() | ||
36 | .filter_map(|l| check_line(l).err()) | ||
37 | .sum(); | ||
38 | println!("Ex1: the result is {}", ex1); | ||
39 | } | ||
40 | |||
41 | fn ex2(content: &str) { | ||
42 | let mut ex2: Vec<u64> = | ||
43 | content.lines() | ||
44 | .filter_map(|l| check_line(l).ok()) | ||
45 | .map(|v| v.iter().rev().fold(0, |a,p| a*5 + SCORE2.get(p).unwrap())) | ||
46 | .collect(); | ||
47 | ex2.sort(); | ||
48 | println!("Ex2: the result is {}", ex2[ex2.len()/2]); | ||
49 | } | ||
50 | |||
51 | fn check_line(line: &str) -> Result<Vec<u8>,u32> { | ||
52 | let acc = Ok(Vec::with_capacity(line.len())); | ||
53 | line.bytes().fold(acc, |a,c| match a { | ||
54 | Ok(mut a) => { | ||
55 | match c { | ||
56 | b'(' => { a.push(b')'); Ok(a) }, | ||
57 | b'[' | b'{' | b'<' => { a.push(c+2); Ok(a) }, | ||
58 | b')' | b']' | b'}' | b'>' => | ||
59 | if a.pop().filter(|&x| x == c).is_some() { | ||
60 | Ok(a) | ||
61 | } else { | ||
62 | Err(*SCORE1.get(&c).unwrap()) | ||
63 | }, | ||
64 | _ => unreachable!() | ||
65 | } | ||
66 | }, | ||
67 | Err(_) => a | ||
68 | }) | ||
69 | } | ||