solution: day2

This commit is contained in:
2023-01-26 15:34:01 +01:00
parent 000000208b
commit 00000030e7
2 changed files with 83 additions and 0 deletions

79
src/bin/02.rs Normal file
View File

@@ -0,0 +1,79 @@
use hashbrown::HashMap;
use itertools::Itertools;
fn direction(d: char) -> (isize, isize) {
match d {
'U' => (-1, 0),
'D' => (1, 0),
'L' => (0, -1),
'R' => (0, 1),
_ => unreachable!(),
}
}
pub fn part_one(input: &str) -> Option<isize> {
let (mut y, mut x) = (1, 1);
let digits: HashMap<(isize, isize), isize> = (0..=2)
.cartesian_product(0..=2)
.map(|(y, x)| ((y, x), y * 3 + x + 1))
.collect();
let mut res = 0;
for line in input.lines() {
res *= 10;
for c in line.chars() {
let (dy, dx) = direction(c);
let (ny, nx) = (y + dy, x + dx);
if digits.contains_key(&(ny, nx)) {
(y, x) = (ny, nx);
}
}
res += digits[&(y, x)];
}
Some(res)
}
pub fn part_two(input: &str) -> Option<String> {
let (mut y, mut x) = (2, 0);
#[rustfmt::skip]
let digits = HashMap::<(isize, isize), char>::from([
((0, 2), '1'), ((1, 1), '2'), ((1, 2), '3'), ((1, 3), '4'),
((2, 0), '5'), ((2, 1), '6'), ((2, 2), '7'), ((2, 3), '8'),
((2, 4), '9'), ((3, 1), 'A'), ((3, 2), 'B'), ((3, 3), 'C'),
((4, 2), 'D'),
]);
let mut res = String::new();
for line in input.lines() {
for c in line.chars() {
let (dy, dx) = direction(c);
let (ny, nx) = (y + dy, x + dx);
if digits.contains_key(&(ny, nx)) {
(y, x) = (ny, nx);
}
}
res.push(digits[&(y, x)]);
}
Some(res)
}
fn main() {
let input = &aoc::read_file("inputs", 2);
aoc::solve!(1, part_one, input);
aoc::solve!(2, part_two, input);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let input = aoc::read_file("examples", 2);
assert_eq!(part_one(&input), Some(1985));
}
#[test]
fn test_part_two() {
let input = aoc::read_file("examples", 2);
assert_eq!(part_two(&input), Some("5DB3".to_string()));
}
}

4
src/examples/02.txt Normal file
View File

@@ -0,0 +1,4 @@
ULL
RRDDD
LURDL
UUUUD