[TASK] Solved day 2

This commit is contained in:
2020-12-02 09:18:39 +01:00
parent 5c8e1324e9
commit 4cc35ef3e5
8 changed files with 1130 additions and 2 deletions

View File

@@ -35,8 +35,6 @@ fn find_pairs_summing_to(nums: &Vec<u32>, target: u32) -> (u32, u32) {
fn find_triplet_summing_to(nums: &Vec<u32>, target: u32) -> (u32, u32, u32){
for i in 0..nums.len() {
for j in (0..nums.len()).rev() {

64
src/day2.rs Normal file
View File

@@ -0,0 +1,64 @@
use super::util;
use regex::{Regex, Captures};
use std::ops::BitXor;
pub fn solve() {
let lines = util::read_file("input/day2.txt");
let passwords: Vec<Password> = lines.iter().map(|p| parse(p)).collect();
let part1 = passwords.iter().filter(|p| p.is_valid()).count();
println!("Day 2 Part 1: {}", part1);
let part2 = passwords.iter().filter(|p| p.is_valid2()).count();
println!("Day 2 Part 2: {}", part2);
}
fn parse(line: &String) -> Password {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(\d+)-(\d+) ([a-zA-Z]): ([a-zA-Z]+)$").unwrap();
}
if !RE.is_match(line.as_str()) {
panic!("Invalid line: {}", line);
}
let caps = RE.captures(line).unwrap();
return Password {
min: get_capture(&caps, 1).parse::<u32>().unwrap(),
max: get_capture(&caps, 2).parse::<u32>().unwrap(),
c: get_capture(&caps, 3).chars().next().unwrap(),
password: String::from(get_capture(&caps, 4))
}
}
fn get_capture(caps: &Captures, id: usize) -> String {
return caps.get(id).map_or(String::from(""), |m| String::from(m.as_str()));
}
// #[derive(Debug)]
struct Password {
pub min: u32,
pub max: u32,
pub c: char,
pub password: String
}
impl Password {
fn is_valid(&self) -> bool {
let occ = self.password.chars().filter(|pc| pc == &self.c).count() as u32;
return occ >= self.min && occ <= self.max;
}
fn is_valid2(&self) -> bool {
return (self.password.chars().nth((self.min - 1) as usize) == Option::from(self.c)).bitxor(
self.password.chars().nth((self.max - 1) as usize) == Option::from(self.c));
}
}

5
src/dayX.rs Normal file
View File

@@ -0,0 +1,5 @@
use super::util;
pub fn solve() {
let lines = util::read_file("input/dayX.txt");
}

View File

@@ -1,7 +1,9 @@
use std::time::Instant;
#[macro_use] extern crate lazy_static;
mod util;
mod day1;
mod day2;
fn main() {
@@ -13,11 +15,13 @@ fn main() {
if day_arg_idx.is_some() {
match args[day_arg_idx.unwrap() + 1].parse::<u8>().unwrap() {
1 => day1::solve(),
2 => day2::solve(),
_ => println!("This day is not yet implemented")
}
} else {
// Solve all days:
day1::solve();
day2::solve();
}
println!("Execution took {} μs", now.elapsed().as_micros());