Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day8 2023 #221

Merged
merged 9 commits into from
Dec 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions inputs/2023/day8_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
LR

11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
5 changes: 5 additions & 0 deletions results/2023.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,10 @@
"day": 7,
"part1": "250254244",
"part2": "250087440"
},
{
"day": 8,
"part1": "13771",
"part2": "13129439557681"
}
]
157 changes: 157 additions & 0 deletions src/aoc2023/day8.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
use std::collections::HashMap;

use crate::aoc2023::Aoc2023;
use crate::traits::days::Day8;
use crate::traits::ParseInput;
use crate::traits::Solution;

#[derive(Debug, Clone, Copy)]
enum Direction {
Left,
Right,
}

#[derive(Debug)]
pub struct GameDef {
instructions: Vec<Direction>,
edges: HashMap<String, (String, String)>,
}

impl ParseInput<Day8> for Aoc2023 {
type Parsed = GameDef;

fn parse_input(input: &str) -> Self::Parsed {
let mut iter = input.lines();

let instructions = iter
.next()
.unwrap()
.trim()
.bytes()
.map(|b| match b {
b'L' => Direction::Left,
b'R' => Direction::Right,
_ => unreachable!(),
})
.collect();

iter.next().unwrap(); // skip empty line

let edges = iter
.map(|line| {
let src = line[0..3].to_owned();
let left = line[7..10].to_owned();
let right = line[12..15].to_owned();
(src, (left, right))
})
.collect();

GameDef {
instructions,
edges,
}
}
}

impl Solution<Day8> for Aoc2023 {
type Part1Output = u32;
type Part2Output = usize;

fn part1(input: &GameDef) -> u32 {
let mut current = "AAA";
let mut inst_stream = InstIterator::new(&input.instructions);

let mut step = 0;
while current != "ZZZ" {
step += 1;
let next = input.edges.get(current).unwrap();
match inst_stream.next().1 {
Direction::Left => {
current = &next.0;
}
Direction::Right => {
current = &next.1;
}
}
}
step
}

fn part2(input: &GameDef) -> usize {
let mut factors = Vec::new();
for key in input.edges.keys() {
if !key.ends_with('A') {
continue;
}

let mut current = key;
let mut inst_stream = InstIterator::new(&input.instructions);
let mut states = HashMap::new();
let mut step = 0usize;

loop {
let (iter_state, next_dir) = inst_stream.next();
// iter_state == 0 is a complete hack, but it works
if current.ends_with('Z') && iter_state == 0 {
if let Some(&previous_step) = states.get(&current) {
let delta = step - previous_step;
assert_eq!(previous_step, delta);
factors.push(delta);
break;
} else {
states.insert(current, step);
}
}
step += 1;

let next = input.edges.get(current).unwrap();
match next_dir {
Direction::Left => {
current = &next.0;
}
Direction::Right => {
current = &next.1;
}
}
}
}
lcm(&factors)
}
}

struct InstIterator<'d> {
state: usize,
data: &'d [Direction],
}
impl<'d> InstIterator<'d> {
fn new(data: &'d [Direction]) -> Self {
InstIterator { state: 0, data }
}

fn next(&mut self) -> (usize, Direction) {
let state = self.state;
let value = self.data[state];
self.state = (self.state + 1) % self.data.len();
(state, value)
}
}

pub fn lcm(nums: &[usize]) -> usize {
assert!(!nums.is_empty());

let mut res = nums[0];
for &b in &nums[1..] {
res = res * b / gcd(res, b);
}
res
}

fn gcd(mut a: usize, mut b: usize) -> usize {
loop {
if b == 0 {
return a;
}

(a, b) = (b, a % b);
}
}
2 changes: 2 additions & 0 deletions src/aoc2023/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod day4;
pub mod day5;
pub mod day6;
pub mod day7;
pub mod day8;

pub fn run_solution_for_day(day: u32, input: &str, results: Option<Results>) -> Option<TimingData> {
let r = results
Expand All @@ -24,6 +25,7 @@ pub fn run_solution_for_day(day: u32, input: &str, results: Option<Results>) ->
5 => run::<Aoc2023, Day5>(input, r),
6 => run::<Aoc2023, Day6>(input, r),
7 => run::<Aoc2023, Day7>(input, r),
8 => run::<Aoc2023, Day8>(input, r),
_ => return None,
};
Some(elapsed)
Expand Down