-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
73 lines (62 loc) · 1.9 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
pub fn main() {
let data = include_str!("input.txt");
let mut cards = Vec::with_capacity(250);
cards.extend(data.lines().map(score_scratchcard));
println!("Part 1: {}", part_one(&cards));
println!("Part 2: {}", part_two(&cards));
}
fn part_one(cards: &[usize]) -> u32 {
cards.iter().map(|&wins| scratchcard_value(wins)).sum()
}
fn part_two(cards: &[usize]) -> u32 {
let mut queue = [0; 250];
queue.iter_mut().take(cards.len()).for_each(|q| *q = 1);
cards.iter().enumerate().fold(0, |acc, (i, &wins)| {
let current = queue[i];
queue
.iter_mut()
.skip(i + 1)
.take(wins)
.for_each(|q| *q += current);
acc + current
})
}
fn score_scratchcard(s: &str) -> usize {
let (_, numbers) = s.split_once(": ").unwrap();
let (winning_numbers, given_numbers) = numbers.split_once(" | ").unwrap();
let numbers = winning_numbers
.split_whitespace()
.map(|n| n.parse::<u32>().unwrap());
let mut winning_numbers = Vec::with_capacity(10);
winning_numbers.extend(numbers);
given_numbers
.split_whitespace()
.map(|n| n.parse::<u32>().unwrap())
.filter(|g| winning_numbers.contains(g))
.count()
}
const fn scratchcard_value(wins: usize) -> u32 {
if wins == 0 {
return 0;
}
1 << (wins - 1)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one() {
let data = include_str!("test.txt");
let mut cards = Vec::with_capacity(250);
cards.extend(data.lines().map(score_scratchcard));
assert_eq!(13, part_one(&cards));
}
#[test]
fn two() {
let data = include_str!("test.txt");
let mut cards = Vec::with_capacity(250);
cards.extend(data.lines().map(score_scratchcard));
assert_eq!(30, part_two(&cards));
}
}