feat: added day 3 part 1 and 2
Signed-off-by: Louis Vallat <contact@louis-vallat.fr>
This commit is contained in:
parent
da36b80be4
commit
1b9129af6e
@ -11,7 +11,7 @@ jobs:
|
||||
name: Challenge for day
|
||||
strategy:
|
||||
matrix:
|
||||
day_number: [1, 2]
|
||||
day_number: [1, 2, 3]
|
||||
runs-on: rust-bookworm
|
||||
steps:
|
||||
- name: Check out repository code
|
||||
|
7
day3/Cargo.toml
Normal file
7
day3/Cargo.toml
Normal file
@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "day3"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
regex = "1.11.1"
|
57
day3/src/main.rs
Normal file
57
day3/src/main.rs
Normal file
@ -0,0 +1,57 @@
|
||||
use regex::Regex;
|
||||
use std::{env, fs};
|
||||
|
||||
fn read_input(path: &str) -> String {
|
||||
fs::read_to_string(path).expect("Cannot read file.")
|
||||
}
|
||||
|
||||
fn parse_input(input: &str) -> Vec<&str> {
|
||||
Regex::new(r"do\(\)|don't\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)")
|
||||
.unwrap()
|
||||
.find_iter(input)
|
||||
.map(|m| m.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn get_mul_result(mul_instruction: &str) -> u32 {
|
||||
let str_tuple = &mul_instruction[4..mul_instruction.len() - 1]
|
||||
.split_once(",")
|
||||
.unwrap();
|
||||
str_tuple.0.parse::<u32>().unwrap() * str_tuple.1.parse::<u32>().unwrap()
|
||||
}
|
||||
|
||||
fn part_1(instructions: &Vec<&str>) -> u32 {
|
||||
instructions
|
||||
.iter()
|
||||
.filter_map(|s| match s.chars().nth(0) {
|
||||
Some('m') => Some(get_mul_result(s)),
|
||||
_ => None,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn part_2(instructions: &Vec<&str>) -> u32 {
|
||||
let mut enabled = true;
|
||||
let mut sum = 0;
|
||||
for instruction in instructions {
|
||||
if *instruction == "do()" {
|
||||
enabled = true;
|
||||
} else if *instruction == "don't()" {
|
||||
enabled = false;
|
||||
} else if enabled {
|
||||
sum += get_mul_result(instruction);
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
for arg in args.iter().skip(1) {
|
||||
let input = read_input(&arg);
|
||||
let instructions = parse_input(&input);
|
||||
println!("[{}]", &arg);
|
||||
println!("\t[Part 1] => Answer is '{}'.", part_1(&instructions));
|
||||
println!("\t[Part 2] => Answer is '{}'.", part_2(&instructions));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user