diff options
author | tomsmeding <tom.smeding@gmail.com> | 2018-12-02 11:09:42 +0100 |
---|---|---|
committer | tomsmeding <tom.smeding@gmail.com> | 2018-12-02 11:09:42 +0100 |
commit | 5fe5f27b2882d0e7628d4374ddbc888417220b60 (patch) | |
tree | 3b0b1592889d481268369073f9a460aae9a71a2a /2018/src | |
parent | 35160c9e759bb7ab5d478074f417305012c779be (diff) |
Day 2
Diffstat (limited to '2018/src')
-rw-r--r-- | 2018/src/day2.rs | 64 | ||||
-rw-r--r-- | 2018/src/main.rs | 19 |
2 files changed, 77 insertions, 6 deletions
diff --git a/2018/src/day2.rs b/2018/src/day2.rs new file mode 100644 index 0000000..6564938 --- /dev/null +++ b/2018/src/day2.rs @@ -0,0 +1,64 @@ +use std::io; +use std::io::BufRead; +use std::collections::HashMap; + +fn close_enough(a: &str, b: &str) -> bool { + let mut num = 0; + + for (ch1, ch2) in a.chars().zip(b.chars()) { + if ch1 != ch2 { + num += 1; + if num > 1 { return false; } + } + } + + return num == 1; +} + +pub fn main<T: BufRead>(reader: T) -> io::Result<()> { + let lines: Vec<String> = reader.lines().map(|l| l.unwrap()).collect(); + + let mut num2: i64 = 0; + let mut num3: i64 = 0; + + for line in &lines { + let mut hist = HashMap::new(); + + for ch in line.chars() { + let value: i64 = *hist.get(&ch).unwrap_or(&0) + 1; + hist.insert(ch, value); + } + + let mut have2 = false; + let mut have3 = false; + for &num in hist.values() { + if num == 2 { have2 = true; } + if num == 3 { have3 = true; } + } + + num2 += have2 as i64; + num3 += have3 as i64; + } + + println!("{}", num2 * num3); + + // TODO: Can this be faster than n^2? + for line1 in &lines { + for line2 in &lines { + if !close_enough(&line1, &line2) { continue; } + + let mut ans = String::new(); + + for (ch1, ch2) in line1.chars().zip(line2.chars()) { + if ch1 == ch2 { + ans.push(ch1); + } + } + + println!("{}", ans); + return Ok(()) + } + } + + Ok(()) +} diff --git a/2018/src/main.rs b/2018/src/main.rs index 7e683ca..162a56e 100644 --- a/2018/src/main.rs +++ b/2018/src/main.rs @@ -7,10 +7,12 @@ use std::process::exit; use argparse::{ArgumentParser, StoreTrue, Store}; mod day1; +mod day2; fn day_switch<T: BufRead>(day: i32, reader: T) -> io::Result<()> { match day { 1 => day1::main(reader), + 2 => day2::main(reader), _ => Err(Error::new(ErrorKind::Other, "Invalid day")) } } @@ -65,13 +67,18 @@ fn main() -> io::Result<()> { } error_handler(|| - match day_string.parse::<i32>() { - Ok(day) => run_day(day, &options), - Err(_) => { - for day in 1..1 { - run_day(day, &options)?; + if day_string.len() == 0 { + for day in 1..3 { + run_day(day, &options)?; + } + Ok(()) + } else { + match day_string.parse::<i32>() { + Ok(day) => run_day(day, &options), + Err(_) => { + println!("Invalid day argument"); + exit(1) } - Ok(()) } } ) |