Skip to content

Commit

Permalink
2023-04: Solve first puzzle
Browse files Browse the repository at this point in the history
  • Loading branch information
MLNW committed Dec 4, 2023
1 parent 3a1947a commit 4431b87
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
6 changes: 6 additions & 0 deletions 2023-rust/data/examples/04.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
72 changes: 72 additions & 0 deletions 2023-rust/src/bin/04.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use itertools::Itertools;

advent_of_code::solution!(4);

struct ScratchCard {
index: u32,
winning_numbers: Vec<u32>,
numbers: Vec<u32>,
}

impl ScratchCard {
pub fn points(&self) -> u32 {
let fold = self
.winning_numbers
.iter()
.map(|number| self.numbers.contains(number))
.filter(|contained| *contained)
.fold(1, |acc, _| acc * 2);
fold / 2
}
}

pub fn part_one(input: &str) -> Option<u32> {
parse_input(input)
.iter()
.map(|card| card.points())
.reduce(|acc, points| acc + points)
}

pub fn part_two(input: &str) -> Option<u32> {
None
}

fn parse_input(input: &str) -> Vec<ScratchCard> {
input
.lines()
.filter_map(|line| line.strip_prefix("Card"))
.filter_map(|line| line.split_once(':'))
.map(|(index, numbers)| {
let (winning, mine) = numbers.split_once('|').unwrap();
ScratchCard {
index: index.trim().parse().unwrap(),
winning_numbers: parse_numbers(winning),
numbers: parse_numbers(mine),
}
})
.collect_vec()
}

fn parse_numbers(numbers: &str) -> Vec<u32> {
numbers
.split_whitespace()
.map(|number| number.parse().unwrap())
.collect_vec()
}

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

#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(13));
}

#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
}
}

0 comments on commit 4431b87

Please sign in to comment.