Created
January 22, 2022 05:51
-
-
Save neofight78/33cd20eb64335e3ec1432600065fa442 to your computer and use it in GitHub Desktop.
Advent of Code 2020 - Day 2: Password Philosophy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Line<'a> { | |
lower: usize, | |
upper: usize, | |
letter: char, | |
password: &'a str, | |
} | |
impl<'a> From<&'a str> for Line<'a> { | |
fn from(l: &'a str) -> Self { | |
let (policy, password) = l.split_once(": ").unwrap(); | |
let (range, letter) = policy.split_once(' ').unwrap(); | |
let (lower, upper) = range.split_once('-').unwrap(); | |
Self { | |
lower: lower.parse().unwrap(), | |
upper: upper.parse().unwrap(), | |
letter: letter.chars().next().unwrap(), | |
password, | |
} | |
} | |
} | |
fn main() { | |
let list = INPUT.lines().map(Line::from).collect::<Vec<_>>(); | |
println!( | |
"Part 1 (Sled policy): {}", | |
list.iter().filter(sled_policy).count() | |
); | |
println!( | |
"Part 2 (Toboggan policy): {}", | |
list.iter().filter(toboggan_policy).count() | |
); | |
} | |
fn sled_policy(line: &&Line) -> bool { | |
let count = line.password.chars().filter(|&c| c == line.letter).count(); | |
count >= line.lower && count <= line.upper | |
} | |
fn toboggan_policy(line: &&Line) -> bool { | |
(line.password.chars().nth(line.lower - 1).unwrap() == line.letter) | |
^ (line.password.chars().nth(line.upper - 1).unwrap() == line.letter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment