day3 made testable

This commit is contained in:
Dylan Thies
2023-08-31 19:29:31 -04:00
parent f8ce0e6253
commit a4408d7d16

View File

@@ -1,38 +1,31 @@
#![warn(clippy::all, clippy::pedantic)] #![warn(clippy::all, clippy::pedantic)]
use std::fs::File; use std::fs;
use std::io::{prelude::*, BufReader};
fn main() -> std::io::Result<()> { fn part1(input: &str) -> String {
//Read in file input
let file = File::open("input")?; .lines()
let reader = BufReader::new(file); .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::<i32>()
.to_string()
}
/* fn part2(input: &str) -> String {
let value = reader input
.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::<i32>();
println!("Part 1: {value}");
*/
//part 2
// fold the lines into groups of three
let value = reader
.lines() .lines()
.fold(Vec::new(), |mut acc: Vec<Vec<String>>, line| { .fold(Vec::new(), |mut acc: Vec<Vec<String>>, line| {
if acc.is_empty() || acc.last().unwrap().len() == 3 { if acc.is_empty() || acc.last().unwrap().len() == 3 {
acc.push(Vec::new()); acc.push(Vec::new());
} }
acc.last_mut().unwrap().push(line.unwrap()); acc.last_mut().unwrap().push(line.to_owned());
acc acc
}) })
.iter() .iter()
@@ -57,10 +50,41 @@ fn main() -> std::io::Result<()> {
_ => 0, _ => 0,
} }
}) })
.sum::<i32>(); .sum::<i32>()
println!("Part 2: {value}"); .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 letter in the groups
// find common letters in the first 2 then find the common in the third // find common letters in the first 2 then find the common in the third
// sum the common letters // sum the common letters
Ok(()) 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");
}
}