Skip to content

Instantly share code, notes, and snippets.

@skjalgsm
Created January 6, 2024 13:49
Show Gist options
  • Save skjalgsm/403c985f22129f2009f4e5349bdd0b33 to your computer and use it in GitHub Desktop.
Save skjalgsm/403c985f22129f2009f4e5349bdd0b33 to your computer and use it in GitHub Desktop.
Advent of code day 1 part1 rust
use tracing;
use std::fs;
use miette::Result;
use crate::aoc_error;
use std::cmp::max;
pub fn run() {
let contents = fs::read_to_string("2023-day-02-part2")
.expect("Should have been able to read the file");
let result = calculate(contents);
match result {
Ok(v) => println!("Result is: {v:?}"),
Err(e) => println!("Error!: {e:?}")
}
}
#[tracing::instrument]
fn calculate(input : String) -> Result<u32, aoc_error::AoCError> {
let mut sum = 0;
let lines = input.lines();
for line in lines {
let game_and_cubes: Vec<&str> = line.split(':').collect();
//let game = game_and_cubes[0];
let cubes = game_and_cubes[1];
let mut red: u32 = 0;
let mut blue: u32 = 0;
let mut green: u32 = 0;
let sets = cubes.split(';');
for set in sets {
let cubes = set.split(',');
for cube in cubes {
//dbg!(cube.trim());
let count_name: Vec<&str> = cube.trim().split(' ').collect();
let mut count: u32 = 0;
match count_name[0].parse::<u32>() {
Ok(n) => count = n,
Err(_) => println!("Expected number but got {}", count_name[0])
}
let cube_name = count_name[1];
match cube_name {
"red" => {
red = max(red, count);
}
"blue" => {
blue = max(blue, count);
}
"green" => {
green = max(green, count);
}
_ => {
println!("Unknown cube color {cube_name}")
}
}
}
}
sum += red * green * blue;
}
return miette::Result::<u32, aoc_error::AoCError>::Ok(sum);
}
#[test]
fn it_works() -> miette::Result<()> {
let input = "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green";
assert_eq!(2286, calculate(input.to_string())?);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment