Skip to content

Instantly share code, notes, and snippets.

@s3thi
Created December 4, 2020 08:17
Show Gist options
  • Save s3thi/9c2eb160b85c62a1f4bb186c238dcdd7 to your computer and use it in GitHub Desktop.
Save s3thi/9c2eb160b85c62a1f4bb186c238dcdd7 to your computer and use it in GitHub Desktop.
use regex::Regex;
use std::fs::read_to_string;
fn is_pass_valid_1(min: u32, max: u32, letter: char, pass: &str) -> bool {
let mut letter_count = 0;
for c in pass.chars() {
if c == letter {
letter_count = letter_count + 1;
}
}
return letter_count >= min && letter_count <= max;
}
fn is_pass_valid_2(pos1: u32, pos2: u32, letter: char, pass: &str) -> bool {
let letter1 = pass.chars().nth(pos1 as usize - 1).unwrap();
let letter2 = pass.chars().nth(pos2 as usize - 1).unwrap();
return (letter1 == letter || letter2 == letter) && !(letter1 == letter && letter2 == letter);
}
fn main() {
let input = read_to_string("input.txt").unwrap();
let re =
Regex::new(r"(?P<min>\d+)-(?P<max>\d+) (?P<letter>[[:alpha:]]): (?P<pass>[[:alpha:]]+)")
.unwrap();
let mut valid_count_1 = 0;
let mut valid_count_2 = 0;
let mut total_count = 0;
for line in input.lines() {
let captures = re.captures(line).unwrap();
let min = captures
.name("min")
.unwrap()
.as_str()
.parse::<u32>()
.unwrap();
let max = captures
.name("max")
.unwrap()
.as_str()
.parse::<u32>()
.unwrap();
let letter = captures
.name("letter")
.unwrap()
.as_str()
.chars()
.next()
.unwrap();
let pass = captures.name("pass").unwrap().as_str();
total_count = total_count + 1;
if is_pass_valid_1(min, max, letter, pass) {
valid_count_1 = valid_count_1 + 1;
}
if is_pass_valid_2(min, max, letter, pass) {
valid_count_2 = valid_count_2 + 1;
}
}
println!(
"Valid passwords for policy 1: {}/{}",
valid_count_1, total_count
);
println!(
"Valid passwords for policy 2: {}/{}",
valid_count_2, total_count
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment