diff --git a/.gitea/workflows/build_and_run.yml b/.gitea/workflows/build_and_run.yml index b46b6f2..8a30cbe 100644 --- a/.gitea/workflows/build_and_run.yml +++ b/.gitea/workflows/build_and_run.yml @@ -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 diff --git a/day3/Cargo.toml b/day3/Cargo.toml new file mode 100644 index 0000000..0275d9d --- /dev/null +++ b/day3/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "day3" +version = "0.1.0" +edition = "2021" + +[dependencies] +regex = "1.11.1" diff --git a/day3/src/main.rs b/day3/src/main.rs new file mode 100644 index 0000000..b5b70cd --- /dev/null +++ b/day3/src/main.rs @@ -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::().unwrap() * str_tuple.1.parse::().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 = 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)); + } +}