summary refs log tree commit diff
path: root/02
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@gmail.com>2020-12-02 20:50:05 -0800
committerIrene Knapp <ireneista@gmail.com>2020-12-02 20:50:05 -0800
commit217a60c017cf54226653321c8cb5a0f844b2101d (patch)
tree304ff83605ee9d5d15fcd4377f2b82bc7cc48bdb /02
parent55e038a16ff2a142c2144850c5bbf1ea8b5cc473 (diff)
Day 2
Diffstat (limited to '02')
-rw-r--r--02/Cargo.toml9
-rw-r--r--02/src/main.rs75
2 files changed, 84 insertions, 0 deletions
diff --git a/02/Cargo.toml b/02/Cargo.toml
new file mode 100644
index 0000000..f4176dc
--- /dev/null
+++ b/02/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "advent_02"
+version = "0.1.0"
+authors = ["Irene Knapp <ireneista@gmail.com>"]
+edition = "2018"
+
+[dependencies]
+advent_lib = { path = "../lib" }
+regex = "1"
diff --git a/02/src/main.rs b/02/src/main.rs
new file mode 100644
index 0000000..5bcf2c1
--- /dev/null
+++ b/02/src/main.rs
@@ -0,0 +1,75 @@
+use advent_lib::prelude::*;
+
+use regex::Regex;
+use std::convert::TryInto;
+
+
+fn main() -> Result<()> {
+  let mut args = std::env::args();
+  if args.len() != 2 {
+    eprintln!("Usage: advent input");
+  }
+  let _ = args.next();
+  let filename = args.next().unwrap();
+
+  let input = advent_lib::read_lines_file(&filename)?;
+
+  let regex = Regex::new(r"^(\d+)-(\d+) ([a-z]): ([a-z]*)$").unwrap();
+
+  let mut valid_passwords = 0;
+
+  for line in &input {
+    let captures = regex.captures(line).unwrap();
+    let min = captures[1].parse::<i64>()?;
+    let max = captures[2].parse::<i64>()?;
+    let required_char = captures[3].chars().nth(0);
+    let password = &captures[4];
+
+    let mut occurrences = 0;
+    for c in password.chars() {
+      if Some(c) == required_char {
+        occurrences += 1;
+      }
+    }
+
+    if occurrences >= min && occurrences <= max {
+      valid_passwords += 1;
+    }
+  }
+
+  println!("{}", valid_passwords);
+
+  let mut valid_passwords_2 = 0;
+
+  for line in &input {
+    let captures = regex.captures(line).unwrap();
+    let index_a = captures[1].parse::<i64>()?;
+    let index_b = captures[2].parse::<i64>()?;
+    let required_char = captures[3].chars().nth(0);
+    let password = &captures[4];
+
+    let a_is_match =
+            password.len() >= index_a.try_into().unwrap()
+            && required_char
+               == password.chars().nth((index_a - 1).try_into().unwrap());
+    let b_is_match =
+            password.len() >= index_b.try_into().unwrap()
+            && required_char
+               == password.chars().nth((index_b - 1).try_into().unwrap());
+    let mut occurrences = 0;
+    if a_is_match {
+      occurrences += 1;
+    }
+    if b_is_match {
+      occurrences += 1;
+    }
+
+    if occurrences == 1 {
+      valid_passwords_2 += 1;
+    }
+  }
+
+  println!("{}", valid_passwords_2);
+
+  Ok(())
+}