Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proper-error-handling #19

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
use std::env;

use advent_of_code::utils::read;
use advent_of_code::utils::{read, GenericResult};
use anyhow::Context;
use itertools::Itertools;
use paste::paste;

fn main() {
fn main() -> GenericResult<()> {
let args = env::args().collect_vec();
if args.len() != 3 {
panic!("Invalid arguments.");
}

let year = args[1].parse::<u16>().unwrap();
let day = args[2].parse::<u16>().unwrap();
let year = args[1]
.parse::<u16>()
.with_context(|| format!("Cannot parse year \"{}\".", args[1]))?;
let day = args[2]
.parse::<u16>()
.with_context(|| format!("Cannot parse day \"{}\".", args[2]))?;

macro_rules! gen_match {
($year:expr; $($n:expr)+ ) => {
Expand All @@ -21,8 +26,9 @@ fn main() {
#[allow(clippy::zero_prefixed_literal)]
$(
if day == $n {
println!("{:?}", [<day$n>]::combi(&[<day$n>]::parse(&read($year, concat!(stringify!([<day$n>]), ".txt")))));
return;
let data = read($year, concat!(stringify!([<day$n>]), ".txt"));
println!("{:?}", [<day$n>]::combi(&[<day$n>]::parse(&data)?));
return Ok(());
}
)+
panic!(concat!("Invalid day for ", stringify!($year), "."));
Expand All @@ -31,9 +37,10 @@ fn main() {
}

if year == 2018 {
gen_match! {2018; 01 18 22};
gen_match! {2018; 01};
} else if year == 2019 {
} else {
panic!("Invalid year");
panic!("Not implemented");
}

panic!("Invalid year");
}
19 changes: 10 additions & 9 deletions src/y2018/day01.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::iter;
use std::{iter, num::ParseIntError};

use itertools::Itertools;
use num::Integer;

type Parsed = i32;

pub fn parse(raw: &str) -> Vec<Parsed> {
raw.split('\n').map(|x| x.parse().unwrap()).collect()
pub fn parse(raw: &str) -> Result<Vec<Parsed>, ParseIntError> {
raw.split('\n').map(|x| x.parse()).try_collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
Expand All @@ -16,15 +16,15 @@ struct Div {
idx: i16,
}

pub fn combi(parsed: &[Parsed]) -> (u32, u32) {
pub fn combi(parsed: &[Parsed]) -> Option<(u32, u32)> {
let mut freq = iter::once(0).chain(parsed.iter().copied()).collect_vec();

freq.iter_mut().fold(0, |acc, i| {
*i += acc;
*i
});

let sum = freq.pop().unwrap();
let sum = freq.pop()?;

// Assuming that the answer is not in the first iteration.
// Otherwise,
Expand Down Expand Up @@ -77,17 +77,18 @@ pub fn combi(parsed: &[Parsed]) -> (u32, u32) {
None
}
})
.min();
.min()?;

(sum as u32, freq[idx.unwrap().2 as usize] as u32)
Some((sum as u32, freq[idx.2 as usize] as u32))
}

#[cfg(test)]
mod tests {
use super::*;
use crate::utils::*;
#[test]
fn test() {
assert_eq!(combi(&parse(&read(2018, "day01.txt"))), (454, 566));
fn test() -> GenericResult<()> {
assert_eq!(combi(&parse(&read(2018, "day01.txt"))?), Some((454, 566)));
Ok(())
}
}