Day 3: Mull It Over
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Rust
use crate::utils::read_lines;
pub fn solution1() {
let lines = read_lines("src/day3/input.txt");
let sum = lines
.map(|line| {
let mut sum = 0;
let mut command_bytes = Vec::new();
for byte in line.bytes() {
match (byte, command_bytes.as_slice()) {
(b')', [.., b'0'..=b'9']) => {
handle_mul(&mut command_bytes, &mut sum);
}
_ if matches_mul(byte, &command_bytes) => {
command_bytes.push(byte);
}
_ => {
command_bytes.clear();
}
}
}
sum
})
.sum::<usize>();
println!("Sum of multiplication results = {sum}");
}
pub fn solution2() {
let lines = read_lines("src/day3/input.txt");
let mut can_mul = true;
let sum = lines
.map(|line| {
let mut sum = 0;
let mut command_bytes = Vec::new();
for byte in line.bytes() {
match (byte, command_bytes.as_slice()) {
(b')', [.., b'0'..=b'9']) if can_mul => {
handle_mul(&mut command_bytes, &mut sum);
}
(b')', [b'd', b'o', b'(']) => {
can_mul = true;
command_bytes.clear();
}
(b')', [.., b't', b'(']) => {
can_mul = false;
command_bytes.clear();
}
_ if matches_do_or_dont(byte, &command_bytes)
|| matches_mul(byte, &command_bytes) =>
{
command_bytes.push(byte);
}
_ => {
command_bytes.clear();
}
}
}
sum
})
.sum::<usize>();
println!("Sum of enabled multiplication results = {sum}");
}
fn matches_mul(byte: u8, command_bytes: &[u8]) -> bool {
matches!(
(byte, command_bytes),
(b'm', [])
| (b'u', [.., b'm'])
| (b'l', [.., b'u'])
| (b'(', [.., b'l'])
| (b'0'..=b'9', [.., b'(' | b'0'..=b'9' | b','])
| (b',', [.., b'0'..=b'9'])
)
}
fn matches_do_or_dont(byte: u8, command_bytes: &[u8]) -> bool {
matches!(
(byte, command_bytes),
(b'd', [])
| (b'o', [.., b'd'])
| (b'n', [.., b'o'])
| (b'\'', [.., b'n'])
| (b'(', [.., b'o' | b't'])
| (b't', [.., b'\''])
)
}
fn handle_mul(command_bytes: &mut Vec<u8>, sum: &mut usize) {
let first_num_index = command_bytes
.iter()
.position(u8::is_ascii_digit)
.expect("Guarunteed to be there");
let comma_index = command_bytes
.iter()
.position(|&c| c == b',')
.expect("Guarunteed to be there.");
let num1 = bytes_to_num(&command_bytes[first_num_index..comma_index]);
let num2 = bytes_to_num(&command_bytes[comma_index + 1..]);
*sum += num1 * num2;
command_bytes.clear();
}
fn bytes_to_num(bytes: &[u8]) -> usize {
bytes
.iter()
.rev()
.enumerate()
.map(|(i, digit)| (*digit - b'0') as usize * 10usize.pow(i as u32))
.sum::<usize>()
}
Definitely not my prettiest code ever. It would probably look nicer if I used regex or some parsing library, but I took on the self-imposed challenge of not using third party libraries. Also, this is already further than I made it last year!
Python
def process(input, part2=False):
if part2:
input = re.sub(r'don\'t\(\).+?do\(\)', '', input) # remove everything between don't() and do()
total = [ int(i[0]) * int(i[1]) for i in re.findall(r'mul\((\d+),(\d+)\)', input) ]
return sum(total)
Given the structure of the input file, we just have to ignore everything between donβt() and do(), so remove those from the instructions before processing.
Sub was my first instinct too, but I got a bad answer and saw that my input had unbalanced do/donβt.
I couldnβt figure it out in haskell, so I went with bash for the first part
Shell
cat example | grep -Eo "mul\([[:digit:]]{1,3},[[:digit:]]{1,3}\)" | cut -d "(" -f 2 | tr -d ")" | tr "," "*" | paste -sd+ | bc
but this wouldnβt rock anymore in the second part, so I had to resort to python for it
Python
import sys
f = "\n".join(sys.stdin.readlines())
f = f.replace("don't()", "\ndon't()\n")
f = f.replace("do()", "\ndo()\n")
import re
enabled = True
muls = []
for line in f.split("\n"):
if line == "don't()":
enabled = False
if line == "do()":
enabled = True
if enabled:
for match in re.finditer(r"mul\((\d{1,3}),(\d{1,3})\)", line):
muls.append(int(match.group(1)) * int(match.group(2)))
pass
pass
print(sum(muls))
Rust feat. pest
No Zalgo here! I wasted a huge amount of time by not noticing that the second partβs example input was different - my code worked fine but my test failed π€¦ββοΈ
pest.rs is lovely, although part two made my PEG a bit ugly.
part1 = { SOI ~ (mul_expr | junk)+ ~ EOI }
part2 = { (enabled | disabled)+ ~ EOI }
mul_expr = { "mul(" ~ number ~ "," ~ number ~ ")" }
number = { ASCII_DIGIT{1,3} }
junk = _{ ASCII }
on = _{ "do()" }
off = _{ "don't()" }
enabled = _{ (SOI | on) ~ (!(off) ~ (mul_expr | junk))+ }
disabled = _{ off ~ (!(on) ~ junk)+ }
use std::fs;
use color_eyre::eyre;
use pest::Parser;
use pest_derive::Parser;
#[derive(Parser)]
#[grammar = "memory.pest"]
pub struct MemoryParser;
fn parse(input: &str, rule: Rule) -> eyre::Result<usize> {
let sum = MemoryParser::parse(rule, input)?
.next()
.expect("input must be ASCII")
.into_inner()
.filter(|pair| pair.as_rule() == Rule::mul_expr)
.map(|pair| {
pair.into_inner()
.map(|num| num.as_str().parse::<usize>().unwrap())
.product::<usize>()
})
.sum();
Ok(sum)
}
fn part1(filepath: &str) -> eyre::Result<usize> {
let input = fs::read_to_string(filepath)?;
parse(&input, Rule::part1)
}
fn part2(filepath: &str) -> eyre::Result<usize> {
let input = fs::read_to_string(filepath)?;
parse(&input, Rule::part2)
}
fn main() -> eyre::Result<()> {
color_eyre::install()?;
let part1 = part1("d03/input.txt")?;
let part2 = part2("d03/input.txt")?;
println!("Part 1: {part1}\nPart 2: {part2}");
Ok(())
}
Kotlin
fun part1(input: String): Int {
val pattern = "mul\\((\\d{1,3}),(\\d{1,3})\\)".toRegex()
var sum = 0
pattern.findAll(input).forEach { match ->
val first = match.groups[1]?.value?.toInt()!!
val second = match.groups[2]?.value?.toInt()!!
sum += first * second
}
return sum
}
fun part2(input: String): Int {
val pattern = "mul\\((\\d{1,3}),(\\d{1,3})\\)|don't\\(\\)|do\\(\\)".toRegex()
var sum = 0
var enabled = true
pattern.findAll(input).forEach { match ->
if (match.value == "do()") enabled = true
else if (match.value == "don't()") enabled = false
else if (enabled) {
val first = match.groups[1]?.value?.toInt()!!
val second = match.groups[2]?.value?.toInt()!!
sum += first * second
}
}
return sum
}