day 6 turned into testable and rfactored

This commit is contained in:
Dylan Thies
2023-09-01 21:15:22 -04:00
parent ae922f8292
commit 8e5a397307
4 changed files with 68 additions and 34 deletions

3
Cargo.lock generated
View File

@@ -79,6 +79,9 @@ dependencies = [
[[package]] [[package]]
name = "day6" name = "day6"
version = "2022.0.0" version = "2022.0.0"
dependencies = [
"itertools",
]
[[package]] [[package]]
name = "day7" name = "day7"

View File

@@ -8,3 +8,4 @@ repository.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
itertools.workspace = true

View File

@@ -1,40 +1,70 @@
#![warn(clippy::all, clippy::pedantic)] #![warn(clippy::all, clippy::pedantic)]
use std::collections::HashMap; use std::fs;
use std::fs::File;
use std::io::{prelude::*, BufReader};
fn main() -> std::io::Result<()> { use itertools::Itertools;
//Read in file
let file = File::open("input")?;
let reader = BufReader::new(file);
reader.lines().enumerate().for_each(|(line_no, line)| { fn work(input: &str, count: usize) -> String {
let line = line.unwrap(); let array = input.as_bytes();
'checker: for i in 4..line.len() { for x in count..array.len() {
let window = line[(i - 4)..i].to_string(); if array
let mut holder: HashMap<char, bool> = HashMap::new(); .iter()
for c in window.chars() { .enumerate()
if holder.contains_key(&c) { .filter_map(|(pos, val)| {
continue 'checker; if pos >= x - count && pos < x {
Some(val)
} else {
None
} }
holder.insert(c, true); })
.unique()
.count()
== count
{
return x.to_string();
} }
println!("Part 1: line: {line_no} marker at: {i}");
break;
} }
'checker: for i in 14..line.len() { panic!("stuff should have been gotten {input}")
let window = line[(i - 14)..i].to_string(); }
let mut holder: HashMap<char, bool> = HashMap::new();
for c in window.chars() { fn part1(input: &str) -> String {
if holder.contains_key(&c) { work(input, 4)
continue 'checker; }
}
holder.insert(c, true); fn part2(input: &str) -> String {
} work(input, 14)
println!("Part 2: line: {line_no} marker at: {i}"); }
break;
} fn main() -> () {
}); //Read in file
Ok(()) let file = fs::read_to_string("input").unwrap();
println!("Part 1: {}", part1(&file));
println!("Part 2: {}", part2(&file));
}
#[cfg(test)]
mod test {
use super::*;
const INPUT: &[(&str, &str, &str)] = &[
("mjqjpqmgbljsphdztnvjfqwrcgsmlb", "7", "19"),
("bvwbjplbgvbhsrlpgdmjqwftvncz", "5", "23"),
("nppdvjthqldpwncqszvftbrmjlhg", "6", "23"),
("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", "10", "29"),
("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", "11", "26"),
];
#[test]
fn part1_works() {
INPUT
.iter()
.for_each(|(test, ans1, _)| assert_eq!(part1(*test), *ans1))
}
#[test]
fn part2_works() {
INPUT
.iter()
.for_each(|(test, _, ans2)| assert_eq!(part2(*test), *ans2))
}
} }