Skip to content

Commit

Permalink
Solve day 04, part one
Browse files Browse the repository at this point in the history
  • Loading branch information
eljamm committed Jan 13, 2024
1 parent d8f39a6 commit e0c3088
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
6 changes: 6 additions & 0 deletions 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
58 changes: 58 additions & 0 deletions src/bin/04.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
advent_of_code::solution!(4);

// Count the number of winning card in hand
fn count_winning(winning: Vec<&str>, hand: Vec<&str>) -> u32 {
let mut counter = 0;
winning.iter().for_each(|i| {
hand.iter().for_each(|j| {
if *i == *j {
counter += 1;
}
});
});
counter
}

pub fn part_one(input: &str) -> Option<u32> {
input
.lines()
.map(|line| {
let input_line: Vec<_> = line.split(": ").collect();
let numbers: Vec<_> = input_line[1].split(" | ").collect();

let winning: Vec<&str> = numbers[0].split_whitespace().collect();
let hand: Vec<&str> = numbers[1].split_whitespace().collect();

let count = count_winning(winning, hand);
let points = match count {
0 => 0,
_ => 1 << count - 1, // Double by every winning card
};

points
})
.sum::<u32>()
.try_into()
.ok()
}

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

#[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 e0c3088

Please sign in to comment.