a bit more cleanup/refactoring
This commit is contained in:
2 files changed
+20
-11
No files matched your search
+5
-5
@@ -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::<usize>("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::<usize>("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::<usize>("data/day01.txt").unwrap();
|
||||
assert_eq!(count_incrementing_windows(1, &data), 1298);
|
||||
assert_eq!(count_incrementing_windows(3, &data), 1248);
|
||||
}
|
||||
|
||||
+15
-6
@@ -1,11 +1,20 @@
|
||||
use anyhow::Result;
|
||||
use std::fs;
|
||||
use std::{fs, str::FromStr};
|
||||
|
||||
pub fn read_i64s(filename: &str) -> Result<Vec<i64>> {
|
||||
Ok(read_file(filename)?
|
||||
.lines()
|
||||
.map(|s| s.parse::<i64>().expect("i64 parse error"))
|
||||
.collect())
|
||||
pub fn read_data<T: FromStr>(filename: &str) -> Result<Vec<T>> {
|
||||
parse_data(&read_file(filename)?)
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
Reference in new issue
Block a user