From 037e395c588ed39d70fe80c0843d8ba8cd637cce Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 4 Dec 2024 16:39:57 -0800 Subject: [PATCH] day3: disable unicode matching, don't recompile RE for every iteration --- 3/src/main.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/3/src/main.rs b/3/src/main.rs index 3347003..3b5af1c 100644 --- a/3/src/main.rs +++ b/3/src/main.rs @@ -1,4 +1,4 @@ -use regex::Regex; +use regex::bytes::Regex; use std::fs::File; use std::io::{BufRead, BufReader, Lines}; use std::time::{Duration, Instant}; @@ -39,10 +39,11 @@ fn main() { fn problem1(input: Lines) -> u64 { let mut sum = 0u64; + let re = Regex::new(r"(?-u)mul\((\d+),(\d+)\)").unwrap(); for line in input.map(|i| i.unwrap()) { - let re = Regex::new(r"mul\((\d+),(\d+)\)").unwrap(); - for m in re.captures_iter(&line) { - sum += m[1].parse::().unwrap() * m[2].parse::().unwrap(); + let line = line.as_bytes(); + for m in re.captures_iter(line) { + sum += std::str::from_utf8(&m[1]).unwrap().parse::().unwrap() * std::str::from_utf8(&m[2]).unwrap().parse::().unwrap(); } } sum @@ -52,13 +53,14 @@ fn problem1(input: Lines) -> u64 { fn problem2(input: Lines) -> u64 { let mut sum = 0u64; let mut do_mul = true; + let re = Regex::new(r"(?-u)(do\(\)|don't\(\)|mul\((\d+),(\d+)\))").unwrap(); for line in input.map(|i| i.unwrap()) { - let re = Regex::new(r"(do\(\)|don't\(\)|mul\((\d+),(\d+)\))").unwrap(); - for m in re.captures_iter(&line) { - match &m[1] { + let line = line.as_bytes(); + for m in re.captures_iter(line) { + match std::str::from_utf8(&m[1]).unwrap() { "do()" => do_mul = true, "don't()" => do_mul = false, - _ if do_mul => sum += m[2].parse::().unwrap() * m[3].parse::().unwrap(), + _ if do_mul => sum += std::str::from_utf8(&m[2]).unwrap().parse::().unwrap() * std::str::from_utf8(&m[3]).unwrap().parse::().unwrap(), _ => {} } }