diff --git a/src/day01.rs b/src/day01.rs index a376006..78fb353 100644 --- a/src/day01.rs +++ b/src/day01.rs @@ -1,12 +1,12 @@ -use crate::utils; +use crate::utils::read_data; use anyhow::Result; -fn count_incrementing_windows(window: usize, v: &[i64]) -> usize { +fn count_incrementing_windows(window: usize, v: &[usize]) -> usize { v[window..].iter().zip(v).filter(|(b, a)| b > a).count() } pub(crate) fn run() -> Result<(usize, usize)> { - let data = utils::read_i64s("data/day01.txt")?; + let data = read_data::("data/day01.txt")?; Ok(( count_incrementing_windows(1, &data), count_incrementing_windows(3, &data), @@ -19,14 +19,14 @@ mod tests { #[test] fn test_example() { - let data = utils::read_i64s("data/day01-test.txt").unwrap(); + let data = read_data::("data/day01-test.txt").unwrap(); assert_eq!(count_incrementing_windows(1, &data), 7); assert_eq!(count_incrementing_windows(3, &data), 5); } #[test] fn test_my_data() { - let data = utils::read_i64s("data/day01.txt").unwrap(); + let data = read_data::("data/day01.txt").unwrap(); assert_eq!(count_incrementing_windows(1, &data), 1298); assert_eq!(count_incrementing_windows(3, &data), 1248); } diff --git a/src/utils.rs b/src/utils.rs index 898d2fd..b9a3384 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,11 +1,20 @@ use anyhow::Result; -use std::fs; +use std::{fs, str::FromStr}; -pub fn read_i64s(filename: &str) -> Result> { - Ok(read_file(filename)? - .lines() - .map(|s| s.parse::().expect("i64 parse error")) - .collect()) +pub fn read_data(filename: &str) -> Result> { + parse_data(&read_file(filename)?) +} + +pub fn parse_data(s: &str) -> Result> { + let mut ret = Vec::new(); + for l in s.lines() { + let data = match l.parse::() { + Ok(d) => d, + Err(_) => panic!("parse error"), + }; + ret.push(data); + } + Ok(ret) } pub fn read_file(filename: &str) -> Result {