Skip to content

Commit

Permalink
Solved AOC 2024 day 11
Browse files Browse the repository at this point in the history
  • Loading branch information
shrugalic committed Dec 11, 2024
1 parent 21a131b commit 8d7b5a2
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 0 deletions.
Binary file added 2024/input/day11.txt
Binary file not shown.
96 changes: 96 additions & 0 deletions 2024/src/day11.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use std::collections::HashMap;

const INPUT: &str = include_str!("../../2024/input/day11.txt");

pub(crate) fn part1() -> usize {
solve_part1(INPUT)
}

pub(crate) fn part2() -> usize {
solve_part2(INPUT)
}

fn solve_part1(input: &str) -> usize {
Stones::from(input).blink(25).count()
}

fn solve_part2(input: &str) -> usize {
Stones::from(input).blink(75).count()
}

type StoneNum = u64;
type Count = usize;

struct Stones {
stones: HashMap<StoneNum, Count>,
}

impl From<&str> for Stones {
fn from(input: &str) -> Self {
let stones = input
.trim()
.split_whitespace()
.map(|n| (n.parse().unwrap(), 1))
.collect();
Stones { stones }
}
}

impl Stones {
fn count(&self) -> Count {
self.stones.values().map(|count| count).sum()
}

fn blink(mut self, count: u8) -> Self {
for _ in 0..count {
let mut next_stones = HashMap::new();
for (stone, count) in self.stones.drain() {
let next = Stones::blink_single(stone);
*next_stones.entry(next[0]).or_insert(0) += count;
if next.len() == 2 {
*next_stones.entry(next[1]).or_insert(0) += count;
}
}
self.stones = next_stones;
}
self
}

fn blink_single(stone: StoneNum) -> Vec<StoneNum> {
match stone {
0 => vec![1],
n if n.to_string().len() % 2 == 0 => {
let divisor = (10 as StoneNum).pow((n.to_string().len() / 2) as u32);
vec![n / divisor, n % divisor]
}
n => vec![n * 2024],
}
}
}

#[cfg(test)]
mod tests {
use super::*;

const EXAMPLE1: &str = "0 1 10 99 999";
const EXAMPLE2: &str = "125 17";

#[test]
fn test_part1_example1() {
assert_eq!(7, Stones::from(EXAMPLE1).blink(1).count());
}
#[test]
fn test_part1_example2() {
assert_eq!(55_312, Stones::from(EXAMPLE2).blink(25).count());
}

#[test]
fn test_part1() {
assert_eq!(194_557, solve_part1(INPUT));
}

#[test]
fn test_part2() {
assert_eq!(231_532_558_973_909, solve_part2(INPUT));
}
}
2 changes: 2 additions & 0 deletions 2024/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod day07;
mod day08;
mod day09;
mod day10;
mod day11;
mod hash_tile_grid;
mod tile_grid;
mod vec_2d;
Expand All @@ -26,6 +27,7 @@ fn main() {
print_result(8, day08::part1(), day08::part2());
print_result(9, day09::part1(), day09::part2());
print_result(10, day10::part1(), day10::part2());
print_result(11, day11::part1(), day11::part2());
}

fn print_result(day: i32, part1: impl Display, part2: impl Display) {
Expand Down

0 comments on commit 8d7b5a2

Please sign in to comment.