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

2 points

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!

permalink
report
reply
2 points

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.

permalink
report
reply
2 points

Sub was my first instinct too, but I got a bad answer and saw that my input had unbalanced do/don’t.

permalink
report
parent
reply
2 points

I did wonder if that might be the case, I must have been lucky with my input.

permalink
report
parent
reply
5 points

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))
permalink
report
reply
1 point

My first insinct was similar, add line breaks to the do and dont modifiers. But I got toa caught up thinking id have to keep track of the added characters, I wound up just abusing split()-

permalink
report
parent
reply
1 point

Nice, sometimes a few extra linebreaks can do the trick…

permalink
report
parent
reply
2 points

Really cool trick. I did a bunch of regex matching that I’m sure I won’t remember how it works few weeks from now, this is so much readable

permalink
report
parent
reply
1 point
*

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(())
}
permalink
report
reply
3 points
*

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
}
permalink
report
reply
3 points

You can avoid having to escape the backslashes in regexps by using multiline strings:

val pattern = """mul\((\d{1,3}),(\d{1,3})\)""".toRegex()
permalink
report
parent
reply

Advent Of Code

!advent_of_code@programming.dev

Create post

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

  • Follow the programming.dev instance rules
  • Keep all content related to advent of code in some way
  • If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2024 Day 10])
  • When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

Community stats

  • 478

    Monthly active users

  • 109

    Posts

  • 1.1K

    Comments