-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
68 lines (57 loc) · 1.72 KB
/
mod.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
use std::cmp::min;
use itertools::Itertools;
use num::pow;
use crate::utils;
use crate::utils::split_whitespace;
pub fn main() {
part_one();
part_two();
}
fn part_one() {
let start = utils::part_start(1);
println!("Result: {}", get_card_point_sum("d04/input"));
utils::part_end(start);
}
fn part_two() {
let start = utils::part_start(2);
println!("Result: {}", get_won_card_count("d04/input"));
utils::part_end(start);
}
fn get_won_card_count(file_path: &str) -> i32 {
let cards = get_card_values(file_path);
let mut counts: Vec<i32> = vec![1; cards.len()];
for (i, (wins, _)) in cards.iter().enumerate() {
let win_from = i + 1;
let win_to = min(i + *wins as usize, counts.len() - 1);
for j in win_from..=win_to {
counts[j] += counts[i];
}
}
counts.iter().sum()
}
fn get_card_point_sum(file_path: &str) -> i32 {
get_card_values(file_path).iter().map(|vals| vals.1).sum()
}
fn get_card_values(file_path: &str) -> Vec<(i32, i32)> {
utils::get_lines(file_path)
.iter()
.map(|line| line.split_once(':').unwrap().1.trim())
.map(|line| line.split_once('|').unwrap())
.map(|(win, mine)| (split_whitespace::<i32>(win), split_whitespace::<i32>(mine)))
.map(|(win, mine)| win.iter().filter(|&n| mine.contains(n)).count())
.map(|n| (n as i32, if n <= 0 { 0 } else { pow(2, n - 1) }))
.collect_vec()
}
#[cfg(test)]
mod tests {
#[test]
fn example_part_one() {
let res = super::get_card_point_sum("d04/example");
assert_eq!(13, res);
}
#[test]
fn example_part_two() {
let res = super::get_won_card_count("d04/example");
assert_eq!(30, res);
}
}