Skip to content

Commit

Permalink
Do day 3
Browse files Browse the repository at this point in the history
  • Loading branch information
samestep committed Dec 3, 2024
1 parent 3ef914c commit 07b3c40
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 0 deletions.
45 changes: 45 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"

[dependencies]
itertools = "0.13"
regex = "1"
1 change: 1 addition & 0 deletions src/day03/example1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
1 change: 1 addition & 0 deletions src/day03/example2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
6 changes: 6 additions & 0 deletions src/day03/input.txt

Large diffs are not rendered by default.

57 changes: 57 additions & 0 deletions src/day03/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use regex::{Captures, Regex};

fn parse_mul(caps: Captures) -> usize {
caps[1].parse::<usize>().unwrap() * caps[2].parse::<usize>().unwrap()
}

pub fn puzzle1(input: &str) -> usize {
let re = Regex::new(r"mul\((\d+),(\d+)\)");
re.unwrap().captures_iter(input).map(parse_mul).sum()
}

pub fn puzzle2(input: &str) -> usize {
let mut sum = 0;
let mut enabled = true;
let re = Regex::new(r"mul\((\d+),(\d+)\)|do\(\)|don't\(\)");
for caps in re.unwrap().captures_iter(input) {
match &caps[0] {
"do()" => enabled = true,
"don't()" => enabled = false,
_ => {
if enabled {
sum += parse_mul(caps);
}
}
}
}
sum
}

#[cfg(test)]
mod tests {
use super::*;

const EXAMPLE1: &str = include_str!("example1.txt");
const EXAMPLE2: &str = include_str!("example2.txt");
const INPUT: &str = include_str!("input.txt");

#[test]
fn test_puzzle1_example1() {
assert_eq!(puzzle1(EXAMPLE1), 161);
}

#[test]
fn test_puzzle1_input() {
assert_eq!(puzzle1(INPUT), 174103751);
}

#[test]
fn test_puzzle2_example2() {
assert_eq!(puzzle2(EXAMPLE2), 48);
}

#[test]
fn test_puzzle2_input() {
assert_eq!(puzzle2(INPUT), 100411201);
}
}
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod day01;
mod day02;
mod day03;

use std::{env, fs};

Expand All @@ -15,6 +16,9 @@ fn main() {
(2, 1) => day02::puzzle1(&input).to_string(),
(2, 2) => day02::puzzle2(&input).to_string(),

(3, 1) => day03::puzzle1(&input).to_string(),
(3, 2) => day03::puzzle2(&input).to_string(),

_ => panic!("no puzzle {} for day {}", puzzle, day),
};
println!("{}", answer.trim_end());
Expand Down

0 comments on commit 07b3c40

Please sign in to comment.