a bit more cleanup/refactoring

This commit is contained in:
swaits committed 2021-12-01 14:47:05 -07:00
1 parent 2e44119f8e
commit b380ecbabd
2 files changed
+20 -11

No files matched your search

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