Created
January 6, 2024 13:48
-
-
Save skjalgsm/6b4fe2069cc94f3d8458fb1a7d7bde57 to your computer and use it in GitHub Desktop.
Advent of code day 2 part1 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 tracing; | |
use std::fs; | |
use miette::Result; | |
use crate::aoc_error; | |
pub fn run() { | |
let contents = fs::read_to_string("2023-day-02-part1") | |
.expect("Should have been able to read the file"); | |
let result = calculate(contents, 12, 13, 14); | |
match result { | |
Ok(v) => println!("Result is: {v:?}"), | |
Err(e) => println!("Error!: {e:?}") | |
} | |
} | |
#[tracing::instrument] | |
fn calculate(input : String, red : u32, green : u32, blue : u32) -> Result<u32, aoc_error::AoCError> { | |
let mut sum = 0; | |
let lines = input.lines(); | |
let mut game_index = 1; | |
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 allowed : bool = true; | |
let sets = cubes.split(';'); | |
for set in sets { | |
let cubes = set.split(','); | |
for cube in cubes { | |
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" => { | |
allowed &= count <= red; | |
} | |
"blue" => { | |
allowed &= count <= blue; | |
} | |
"green" => { | |
allowed &= count <= green; | |
} | |
_ => { | |
println!("Unknown cube color {cube_name}") | |
} | |
} | |
if !allowed { | |
break; | |
} | |
} | |
} | |
if allowed { | |
sum += game_index; | |
} | |
game_index += 1; | |
} | |
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!(8, calculate(input.to_string(), 12, 13, 14)?); | |
Ok(()) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment