Cleanup for 2022 day 1: Turned into a lib and introduced parse errors instead of silently defaulting to 0
This commit is contained in:
parent
8a8085b8b5
commit
7a90ec700d
2 changed files with 41 additions and 47 deletions
41
2022/day01-calorie_counting/src/lib.rs
Normal file
41
2022/day01-calorie_counting/src/lib.rs
Normal file
|
@ -0,0 +1,41 @@
|
|||
use std::num::ParseIntError;
|
||||
|
||||
fn try_parse_cal_list(list: &str) -> Result<Vec<usize>, ParseIntError> {
|
||||
let mut cals: Vec<_> = list.split("\n\n")
|
||||
.collect::<Vec<&str>>()
|
||||
.iter()
|
||||
.map(|individual_list| individual_list.lines()
|
||||
.map(|n| n.parse::<usize>())
|
||||
.sum::<Result<usize, _>>())
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
cals.sort_by_key(|i| std::cmp::Reverse(*i));
|
||||
Ok(cals)
|
||||
}
|
||||
|
||||
pub fn run(input: &str) -> Result<(usize, usize), ParseIntError> {
|
||||
let elves = try_parse_cal_list(input)?;
|
||||
Ok((elves[0], elves.iter().take(3).sum::<usize>()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn read_file(path: &str) -> String {
|
||||
std::fs::read_to_string(path)
|
||||
.expect("File not Found")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_input() {
|
||||
let list = read_file("tests/sample_input");
|
||||
assert_eq!(run(&list), Ok((24000, 45000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn challenge_input() {
|
||||
let list = read_file("tests/input");
|
||||
assert_eq!(run(&list), Ok((71780, 212489)));
|
||||
}
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
use std::fs;
|
||||
|
||||
fn parse_cal_list(list: String) -> Vec<u32> {
|
||||
let mut cals: Vec<u32> = list.split("\n\n")
|
||||
.collect::<Vec<&str>>()
|
||||
.iter()
|
||||
.map(|individual_list| individual_list.lines()
|
||||
.map(|n| n.parse::<u32>().unwrap_or(0))
|
||||
.sum::<u32>())
|
||||
.collect();
|
||||
|
||||
cals.sort();
|
||||
cals.reverse();
|
||||
cals
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let list = read_file("input");
|
||||
|
||||
let elves = parse_cal_list(list);
|
||||
|
||||
println!("Max: {}", elves[0]);
|
||||
println!("Top 3: {}", elves.iter().take(3).sum::<u32>())
|
||||
}
|
||||
|
||||
fn read_file(path: &str) -> String {
|
||||
fs::read_to_string(path)
|
||||
.expect("File not Found")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_input() {
|
||||
let list = read_file("tests/sample_input");
|
||||
let elves = parse_cal_list(list);
|
||||
|
||||
assert_eq!(elves[0], 24000);
|
||||
assert_eq!(elves.iter().take(3).sum::<u32>(), 45000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn challenge_input() {
|
||||
let list = read_file("tests/input");
|
||||
let elves = parse_cal_list(list);
|
||||
|
||||
assert_eq!(elves[0], 71780);
|
||||
assert_eq!(elves.iter().take(3).sum::<u32>(), 212489);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue