Created
December 1, 2022 09:02
-
-
Save alexfoxgill/077e80efcfcf10556dcb486fc8865192 to your computer and use it in GitHub Desktop.
AoC 2022 Day 1: Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs; | |
fn load_vec(path: &str) -> Vec<String> { | |
fs::read_to_string(path) | |
.expect("Could not read file") | |
.split('\n') | |
.map(|x| String::from(x)) | |
.collect() | |
} | |
fn group_and_sum(strings: Vec<String>) -> Vec<i32> { | |
strings | |
.split(|x| x.is_empty()) | |
.map(|chunk| chunk.iter().map(|x| str::parse::<i32>(x).unwrap()).sum()) | |
.collect::<Vec<_>>() | |
} | |
fn find_max(int_groups: Vec<i32>) -> i32 { | |
*int_groups.iter().max().unwrap() | |
} | |
fn part_one(input: &str) -> i32 { | |
let summed = group_and_sum(load_vec(input)); | |
summed.into_iter().max().unwrap() | |
} | |
fn part_two(input: &str) -> i32 { | |
let mut summed = group_and_sum(load_vec(input)); | |
summed.sort(); | |
summed.iter().rev().take(3).sum() | |
} | |
#[test] | |
fn test_part_one_sample() { | |
let result = part_one("src/day01/sample.txt"); | |
assert_eq!(result, 24000); | |
} | |
#[test] | |
fn test_part_one() { | |
let result = part_one("src/day01/input.txt"); | |
assert_eq!(result, 69501); | |
} | |
#[test] | |
fn test_part_two_sample() { | |
let result = part_two("src/day01/sample.txt"); | |
assert_eq!(result, 45000); | |
} | |
#[test] | |
fn test_part_two() { | |
let result = part_two("src/day01/input.txt"); | |
assert_eq!(result, 202346); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment