diff --git a/day3/src/main.rs b/day3/src/main.rs index f297e34..0f93518 100644 --- a/day3/src/main.rs +++ b/day3/src/main.rs @@ -1,38 +1,31 @@ #![warn(clippy::all, clippy::pedantic)] -use std::fs::File; -use std::io::{prelude::*, BufReader}; +use std::fs; -fn main() -> std::io::Result<()> { - //Read in file - let file = File::open("input")?; - let reader = BufReader::new(file); +fn part1(input: &str) -> String { + input + .lines() + .map(|line| { + let (comp1, comp2) = line.split_at(line.len() / 2); + let duplicate = comp2.chars().find(|c| comp1.contains(*c)).unwrap(); + match duplicate { + n @ 'a'..='z' => (n as i32) - ('a' as i32) + 1_i32, + n @ 'A'..='Z' => (n as i32) - ('A' as i32) + 27_i32, + _ => 0, + } + }) + .sum::() + .to_string() +} - /* - let value = reader - .lines() - .map(|line| { - let line = line.unwrap(); - let (comp1, comp2) = line.split_at(line.len() / 2); - let duplicate = comp2.chars().find(|c| comp1.contains(*c)).unwrap(); - match duplicate { - n @'a'..='z' => (n as i32) - ('a' as i32) + 1_i32, - n @ 'A'..='Z' => (n as i32) - ('A' as i32) + 27_i32, - _ => 0, - } - }) - .sum::(); - println!("Part 1: {value}"); - */ - //part 2 - // fold the lines into groups of three - let value = reader +fn part2(input: &str) -> String { + input .lines() .fold(Vec::new(), |mut acc: Vec>, line| { if acc.is_empty() || acc.last().unwrap().len() == 3 { acc.push(Vec::new()); } - acc.last_mut().unwrap().push(line.unwrap()); + acc.last_mut().unwrap().push(line.to_owned()); acc }) .iter() @@ -57,10 +50,41 @@ fn main() -> std::io::Result<()> { _ => 0, } }) - .sum::(); - println!("Part 2: {value}"); + .sum::() + .to_string() +} + +fn main() -> std::io::Result<()> { + //Read in file + let file = fs::read_to_string("input")?; + + // fold the lines into groups of three + println!("Part 1: {}", part1(&file)); + println!("Part 2: {}", part2(&file)); // find common letter in the groups // find common letters in the first 2 then find the common in the third // sum the common letters Ok(()) } + +#[cfg(test)] +mod test { + use super::*; + + const INPUT: &str = "vJrwpWtwJgWrhcsFMMfFFhFp +jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL +PmmdzqPrVvPwwTWBwg +wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn +ttgJtRGJQctTZtZT +CrZsJsPPZsGzwwsLwLmpwMDw"; + + #[test] + fn part1_works() { + assert_eq!(part1(&INPUT), "157"); + } + + #[test] + fn part2_works() { + assert_eq!(part2(&INPUT), "70"); + } +}