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

optimization for day4 2023 #215

Merged
merged 2 commits into from
Dec 5, 2023
Merged
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
32 changes: 16 additions & 16 deletions src/aoc2023/day4.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
use std::collections::HashMap;
use std::collections::HashSet;

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

#[derive(Debug)]
pub struct Card {
id: u32,
// no need for any id, the index of the card in the deck + 1 is the id
winning: Vec<u32>,
got: Vec<u32>,
}

impl Card {
fn inter_count(&self) -> usize {
let winning: HashSet<_> = self.winning.iter().copied().collect();
let got: HashSet<_> = self.got.iter().copied().collect();
winning.intersection(&got).count()
let mut count = 0;
for g in &self.got {
if self.winning.contains(g) {
count += 1;
}
}
count
}
}

Expand All @@ -28,10 +29,9 @@ impl ParseInput<Day4> for Aoc2023 {
input
.lines()
.map(|line| {
let (before, after) = line.split_at(line.find(": ").unwrap());
let (_, after) = line.split_at(line.find(": ").unwrap());
let after = &after[2..];

let id = before.strip_prefix("Card").unwrap().trim().parse().unwrap();
let (winning, got) = after.split_at(after.find(" | ").unwrap());
let got = &got[3..];

Expand All @@ -44,7 +44,7 @@ impl ParseInput<Day4> for Aoc2023 {
.map(|value| value.trim().parse().unwrap())
.collect();

Card { id, winning, got }
Card { winning, got }
})
.collect()
}
Expand All @@ -65,16 +65,16 @@ impl Solution<Day4> for Aoc2023 {
}

fn part2(input: &Vec<Card>) -> u32 {
let mut counts = HashMap::new();
for card in input {
let mut counts: Vec<u32> = vec![1; input.len()];
for (id, card) in input.iter().enumerate() {
let inter = card.inter_count();
let current_count = *counts.entry(card.id).or_insert(1);
let current_count = counts[id];
for i in 1..=inter {
let id = card.id + i as u32;
*counts.entry(id).or_insert(1) += current_count;
let next_id = id + i;
counts[next_id] += current_count;
}
}

counts.values().sum()
counts.into_iter().sum()
}
}