Hello, I'm working through AOC as a way to learn Rust, and my solution for day 2 part 1 is incredibly slow. As in > 13 seconds.
There are no loops, but is there some operation I'm doing here that is the obvious culprit?
use std::env;
use std::fs;
use regex::Regex;
fn main() {
let args: Vec<String> = env::args().collect();
let file = &args[1];
let contents = fs::read_to_string(file).expect("File read error");
let contents = contents.trim();
let pws: Vec<Password> = contents.split("\n").map(parse_line).filter(|p| is_valid(p)).collect();
println!("{:?}", pws.len())
}
#[derive(Debug, PartialEq)]
struct Password {
first: usize,
second: usize,
character: char,
password: String
}
fn parse_line(line: &str) -> Password {
let re = Regex::new(r"(\d+)-(\d+) (\w): (\w+)").unwrap();
let caps = re.captures(line).unwrap();
let c: Vec<char> = caps[3].chars().collect();
Password {
first: caps[1].parse::<usize>().unwrap(),
second: caps[2].parse::<usize>().unwrap(),
character: c[0],
password: caps[4].to_string()
}
}
fn is_valid(pw: &Password) -> bool {
let cs: Vec<char> = pw.password.chars().collect();
(cs[(pw.first - 1)] == pw.character) ^ (cs[(pw.second - 1)] == pw.character)
}
#[cfg(test)]
mod tests {
use super::is_valid;
use super::parse_line;
use super::Password;
#[test]
fn parsing() {
assert_eq!(
parse_line("1-3 a: abcde"),
Password {
first: 1, second: 3, character: 'a', password: "abcde".to_string()
})
}
#[test]
fn example_1() {
assert_eq!(true, is_valid(&Password {
first: 1, second: 3, character: 'a', password: "abcde".to_string()
}))
}
}