Skip to content

Commit

Permalink
2023-04: Solve second puzzle
Browse files Browse the repository at this point in the history
  • Loading branch information
MLNW committed Dec 4, 2023
1 parent 4431b87 commit f190364
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
9 changes: 5 additions & 4 deletions 2023-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.

| Day | Part 1 | Part 2 |
| :---: | :---: | :---: |
| [Day 1](./src/bin/01.rs) | `64.7µs` | `634.0µs` |
| [Day 2](./src/bin/02.rs) | `40.8µs` | `46.7µs` |
| [Day 3](./src/bin/03.rs) | `426.2µs` | `429.9µs` |
| [Day 1](./src/bin/01.rs) | `64.6µs` | `639.8µs` |
| [Day 2](./src/bin/02.rs) | `41.8µs` | `48.0µs` |
| [Day 3](./src/bin/03.rs) | `430.0µs` | `424.2µs` |
| [Day 4](./src/bin/04.rs) | `98.3µs` | `47.2ms` |

**Total: 1.64ms**
**Total: 48.95ms**
<!--- benchmarking table --->

## Usage
Expand Down
37 changes: 33 additions & 4 deletions 2023-rust/src/bin/04.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use std::collections::{HashMap, VecDeque};

use itertools::Itertools;

advent_of_code::solution!(4);

#[derive(Clone)]
struct ScratchCard {
index: u32,
id: u32,
winning_numbers: Vec<u32>,
numbers: Vec<u32>,
}
Expand All @@ -18,6 +21,16 @@ impl ScratchCard {
.fold(1, |acc, _| acc * 2);
fold / 2
}

pub fn copies(&self) -> Vec<u32> {
self.winning_numbers
.iter()
.map(|number| self.numbers.contains(number))
.filter(|contained| *contained)
.enumerate()
.map(|(i, _)| self.id + i as u32 + 1)
.collect_vec()
}
}

pub fn part_one(input: &str) -> Option<u32> {
Expand All @@ -28,7 +41,22 @@ pub fn part_one(input: &str) -> Option<u32> {
}

pub fn part_two(input: &str) -> Option<u32> {
None
let cards = parse_input(input);

let lookup: HashMap<u32, Vec<u32>> =
cards.iter().map(|card| (card.id, card.copies())).collect();

let mut queue = VecDeque::from(cards.iter().map(|card| card.id).collect::<Vec<u32>>());

let mut total = 0;
while let Some(card) = queue.pop_front() {
total += 1;

let copies = lookup.get(&card).unwrap();
queue.extend(copies);
}

Some(total)
}

fn parse_input(input: &str) -> Vec<ScratchCard> {
Expand All @@ -38,8 +66,9 @@ fn parse_input(input: &str) -> Vec<ScratchCard> {
.filter_map(|line| line.split_once(':'))
.map(|(index, numbers)| {
let (winning, mine) = numbers.split_once('|').unwrap();
let parsed_index: u32 = index.trim().parse().unwrap();
ScratchCard {
index: index.trim().parse().unwrap(),
id: parsed_index - 1,
winning_numbers: parse_numbers(winning),
numbers: parse_numbers(mine),
}
Expand Down Expand Up @@ -67,6 +96,6 @@ mod tests {
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
assert_eq!(result, Some(30));
}
}

0 comments on commit f190364

Please sign in to comment.