From 11744d1fe9721dca3b7fd75abc430535109fa5fd Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Wed, 1 Dec 2021 21:34:51 -0800 Subject: [PATCH] Use anyhow to make try operator feasible in parse and part#. --- 2021/src/day1.rs | 34 +++++++++++++++++----------------- 2021/src/template.rs | 24 +++++++++++++++--------- 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/2021/src/day1.rs b/2021/src/day1.rs index 08e0caa..4962ecb 100644 --- a/2021/src/day1.rs +++ b/2021/src/day1.rs @@ -73,36 +73,34 @@ //! //! Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum? +use anyhow::Result; use aoc_runner_derive::{aoc, aoc_generator}; -/// Reads text file containing one integer per line, and parses them into `Vec`. Any -/// non-number will result in a panice. +/// Reads text file containing one integer per line, and parses them into `Vec`. #[aoc_generator(day1)] -fn parse(input: &str) -> Vec { - input - .split("\n") - .map(|s| s.parse().expect("not a number")) - .collect() +fn parse(input: &str) -> Result> { + input.split("\n").map(|s| Ok(s.parse()?)).collect() } #[aoc(day1, part1)] -fn part1(depths: &[u32]) -> u32 { - depths +fn part1(depths: &[u32]) -> Result { + Ok(depths .windows(2) .map(|s| if s[0] < s[1] { 1 } else { 0 }) - .sum() + .sum()) } #[aoc(day1, part2)] -fn part2(depths: &[u32]) -> u32 { +fn part2(depths: &[u32]) -> Result { let sums: Vec = depths.windows(3).map(|s| s.iter().sum()).collect(); - sums.windows(2) + Ok(sums + .windows(2) .map(|s| if s[0] < s[1] { 1 } else { 0 }) - .sum() + .sum()) } #[test] -fn test_part1() { +fn test_part1() -> Result<()> { assert_eq!( part1(&parse( r#"199 @@ -115,13 +113,14 @@ fn test_part1() { 269 260 263"# - )), + )?)?, 7 ); + Ok(()) } #[test] -fn test_part2() { +fn test_part2() -> Result<()> { assert_eq!( part2(&parse( r#"199 @@ -134,7 +133,8 @@ fn test_part2() { 269 260 263"# - )), + )?)?, 5 ); + Ok(()) } diff --git a/2021/src/template.rs b/2021/src/template.rs index d8a15ad..186a8e6 100644 --- a/2021/src/template.rs +++ b/2021/src/template.rs @@ -1,36 +1,42 @@ +use anyhow::Result; use aoc_runner_derive::{aoc, aoc_generator}; #[aoc_generator(dayX)] -fn parse(input: &str) -> Vec { - todo!("parse") +fn parse(input: &str) -> Result> { + todo!("parse"); + Ok(Vec::new()) } #[aoc(dayX, part1)] -fn part1(depths: &[u32]) -> u32 { - todo!("part1") +fn part1(depths: &[u32]) -> Result { + todo!("part1"); + Ok(()) } /* #[aoc(dayX, part2)] -fn part2(depths: &[u32]) -> u32 { +fn part2(depths: &[u32]) -> Result { todo!("part2") + Ok(()) } */ #[test] -fn test_part1() { +fn test_part1() -> Result<()> { let input = r#" "# .trim(); - assert_eq!(part1(&parse(input)), TODO); + assert_eq!(part1(&parse(input)?)?, TODO); + Ok(()) } /* #[test] -fn test_part2() { +fn test_part2()->Result<()> { let input = r#" "# .trim(); - assert_eq!(part2(&parse(input)), TODO); + assert_eq!(part2(&parse(input)?)?, TODO); +Ok(()) } */