Skip to content

Commit

Permalink
2023: Cleanup day 4
Browse files Browse the repository at this point in the history
  • Loading branch information
connorslade committed Dec 4, 2023
1 parent 996e730 commit 1022e3c
Showing 1 changed file with 20 additions and 25 deletions.
45 changes: 20 additions & 25 deletions aoc_2023/src/day_04.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,68 +11,63 @@ impl Solution for Day04 {
let cards = parse(input);
cards
.iter()
.map(|x| x.count_wins())
.filter(|x| *x > 0)
.map(|x| 2u32.pow(x.saturating_sub(1) as u32))
.filter(|x| x.wins > 0)
.map(|x| 2u32.pow(x.wins.saturating_sub(1) as u32))
.sum::<u32>()
.into()
}

fn part_b(&self, input: &str) -> Answer {
let cards = parse(input);

let mut queue = cards.clone();
let mut queue = (0..cards.len()).collect::<Vec<_>>();
let mut visited = 0;

while let Some(card) = queue.pop() {
let wins = card.count_wins();
while let Some(i) = queue.pop() {
visited += 1;
if wins == 0 {

let card = &cards[i];
if card.wins == 0 {
continue;
}

let num = card.number as usize;
for i in num + 1..=num + wins {
queue.push(cards[i as usize - 1].clone());
for j in 0..card.wins as usize {
queue.push(j + i + 1);
}
}

visited.into()
}
}

#[derive(Clone)]
#[derive(Clone, Hash, PartialEq, Eq)]
struct Card {
number: u8,
winning: Vec<u8>,
scratch: Vec<u8>,
wins: u8,
}

fn parse(input: &str) -> Vec<Card> {
let mut cards = Vec::new();
for line in input.lines() {
let (_, line) = line.split_once(": ").unwrap();
let (winning, scratch) = line.split_once(" | ").unwrap();
let parse = |s: &str| s.split_whitespace().map(|x| x.parse().unwrap()).collect();
let parse = |s: &str| {
s.split_whitespace()
.map(|x| x.parse().unwrap())
.collect::<Vec<u8>>()
};

let winning = parse(winning);
let scratch = parse(scratch);
cards.push(Card {
number: cards.len() as u8 + 1,
winning: parse(winning),
scratch: parse(scratch),
wins: scratch.iter().filter(|x| winning.contains(x)).count() as u8,
});
}

cards
}

impl Card {
fn count_wins(&self) -> usize {
self.scratch
.iter()
.filter(|x| self.winning.contains(x))
.count()
}
}

#[cfg(test)]
mod test {
use common::Solution;
Expand Down

0 comments on commit 1022e3c

Please sign in to comment.