-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.rs
63 lines (53 loc) · 1.6 KB
/
day02.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
use std::fs;
struct PasswordData {
min: usize,
max: usize,
ch: char,
pw: String,
}
impl PasswordData {
fn parse_input(s: &str) -> Option<PasswordData> {
let mut token: Vec<&str> = s.split_whitespace().collect();
let pw = token.pop()?.to_string();
let ch = token.pop()?.chars().next()?;
let minmax: Vec<&str> = token.pop()?.split('-').collect();
let min_fromstr = minmax[0].parse().ok()?;
let max_fromstr = minmax[1].parse().ok()?;
Some(PasswordData {
min: min_fromstr,
max: max_fromstr,
ch,
pw,
})
}
}
struct Solution;
impl Solution {
fn part1(pw_data: &[PasswordData]) -> usize {
pw_data
.iter()
.filter(|pdata| {
let count = pdata.pw.chars().filter(|&c| c == pdata.ch).count();
count >= pdata.min && count <= pdata.max
})
.count()
}
fn part2(pw_data: &[PasswordData]) -> usize {
pw_data
.iter()
.filter(|pdata| {
(pdata.pw.chars().nth(pdata.min - 1).unwrap() == pdata.ch)
^ (pdata.pw.chars().nth(pdata.max - 1).unwrap() == pdata.ch)
})
.count()
}
}
fn main() {
let input: String = fs::read_to_string("./input/day02.txt").expect("File not found!");
let pw_data: Vec<PasswordData> = input
.lines()
.map(|l| PasswordData::parse_input(l).unwrap())
.collect();
println!("p1: {}", Solution::part1(&pw_data));
println!("p2: {}", Solution::part2(&pw_data));
}