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
Gleam
Struggled with the second part as I am still very new to this very cool language, but got there after scrolling for some inspiration.
import gleam/int import gleam/io import gleam/list import gleam/regex import gleam/result import gleam/string import simplifile pub fn main() { let assert Ok(data) = simplifile.read("input.in") part_one(data) |> io.debug part_two(data) |> io.debug } fn part_one(data) { let assert Ok(multiplication_pattern) = regex.from_string("mul\\(\\d{1,3},\\d{1,3}\\)") let assert Ok(digit_pattern) = regex.from_string("\\d{1,3},\\d{1,3}") let multiplications = regex.scan(multiplication_pattern, data) |> list.flat_map(fn(reg) { regex.scan(digit_pattern, reg.content) |> list.map(fn(digits) { digits.content |> string.split(",") |> list.map(fn(x) { x |> int.parse |> result.unwrap(0) }) |> list.reduce(fn(a, b) { a * b }) |> result.unwrap(0) }) }) |> list.reduce(fn(a, b) { a + b }) |> result.unwrap(0) } fn part_two(data) { let data = "do()" <> string.replace(data, "\n", "") <> "don't()" let assert Ok(pattern) = regex.from_string("do\\(\\).*?don't\\(\\)") regex.scan(pattern, data) |> list.map(fn(input) { input.content |> part_one }) |> list.reduce(fn(a, b) { a + b }) }
Nim
From a first glance it was obviously a regex problem.
I’m using tinyre here instead of stdlibre
library just because I’m more familiar with it.import pkg/tinyre proc solve(input: string): AOCSolution[int, int] = var allow = true for match in input.match(reG"mul\(\d+,\d+\)|do\(\)|don't\(\)"): if match == "do()": allow = true elif match == "don't()": allow = false else: let pair = match[4..^2].split(',') let mult = pair[0].parseInt * pair[1].parseInt result.part1 += mult if allow: result.part2 += mult
I shy away from regexes for these parsing problems because part 2 likes to mess those up but here it worked beautifully. Nice and compact solution!
Sorry for the delay posting this one, Ategon seemed to have it covered, so I forgot :D I will do better.
Haskell
Oof, a parsing problem :/ This is some nasty-ass code.
step
is almost the State monad written out explicitly.Solution
import Control.Monad import Data.Either import Data.List import Text.Parsec data Ins = Mul !Int !Int | Do | Dont readInput :: String -> [Ins] readInput = fromRight undefined . parse input "" where input = many ins <* many anyChar ins = choice . map try $ [ Mul <$> (string "mul(" *> arg) <*> (char ',' *> arg) <* char ')', Do <$ string "do()", Dont <$ string "don't()", anyChar *> ins ] arg = do s <- many1 digit guard $ length s <= 3 return $ read s run f = snd . foldl' step (True, 0) where step (e, a) i = case i of Mul x y -> (e, if f e then a + x * y else a) Do -> (True, a) Dont -> (False, a) main = do input <- readInput <$> readFile "input03" print $ run (const True) input print $ run id input
Love to see you chewing through this parsing problem in Haskell, I didn’t dare use Parsec because I wasn’t confident enough.
Why did you decide to have a strict definition ofMul !Int !Int
?My guess is because a linter and/or HLS was suggesting it. I know HLS used to suggest making your fields strict in almost all cases. In this case I have a hunch that it slightly cuts down on memory usage because we use almost all
Mul
s either way. So it does not need to keep the string it is parsed from in memory as part of the thunk.But it probably makes a small/negligible difference here.
Yep, HLS suggested it, and I figured since I’m definitely going to be using all of the values (in part one, at least), why not?
Normally I ignore that kind of nitpicky suggestion though.
Python
Part1:
matches = re.findall(r"(mul\((\d+),(\d+)\))", input) muls = [int(m[1]) * int(m[2]) for m in matches] print(sum(muls))
Part2:
instructions = list(re.findall(r"(do\(\)|don't\(\)|(mul\((\d+),(\d+)\)))", input) mul_enabled = True muls = 0 for inst in instructions: if inst[0] == "don't()": mul_enabled = False elif inst[0] == "do()": mul_enabled = True elif mul_enabled: muls += int(inst[2]) * int(inst[3]) print(muls)
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 did wonder if that might be the case, I must have been lucky with my input.
Python
I’m surprised I don’t see more people taking advantage of
eval
I thought it was pretty slick.import operator import re with open('input.txt', 'r') as file: memory = file.read() matches = re.findall("mul\(\d{1,3},\d{1,3}\)|don't\(\)|do\(\)", memory) enabled = 1 filtered_matches = [] for instruction in matches: if instruction == "don't()": enabled = 0 continue elif instruction == "do()": enabled = 1 continue elif enabled: filtered_matches.append(instruction) multipled = [eval(f"operator.{x}") for x in filtered_matches] print(sum(multiples))
Kotlin
Just the standard Regex stuff. I found this website to be very helpful to write the patterns. (Very useful in general)
fun main() { fun part1(input: List<String>): Int = Regex("""mul\(\d+,\d+\)""").findAll(input.joinToString()).sumOf { with(Regex("""\d+""").findAll(it.value)) { this.first().value.toInt() * this.last().value.toInt() } } fun part2(input: List<String>): Int { var isMultiplyInstructionEnabled = true // by default return Regex("""mul\(\d+,\d+\)|do\(\)|don't\(\)""").findAll(input.joinToString()).fold(0) { acc, instruction -> when (instruction.value) { "do()" -> acc.also { isMultiplyInstructionEnabled = true } "don't()" -> acc.also { isMultiplyInstructionEnabled = false } else -> { if (isMultiplyInstructionEnabled) { acc + with(Regex("""\d+""").findAll(instruction.value)) { this.first().value.toInt() * this.last().value.toInt() } } else acc } } } } val testInputPart1 = readInput("Day03_test_part1") val testInputPart2 = readInput("Day03_test_part2") check(part1(testInputPart1) == 161) check(part2(testInputPart2) == 48) val input = readInput("Day03") part1(input).println() part2(input).println() } ´´´
Uiua
Part 1:
&fras "day3/input.txt" /+≡/×≡⋕≡↘1regex "mul\\((\\d+),(\\d+)\\)"
Part 2:
Filter ← ⍜⊜∘≡⋅""⊸⦷°□ .&fras "day3/input.txt" ∧Filter♭regex"don't\\(\\)?(.*?)(?:do\\(\\)|$)" /+≡/×≡⋕≡↘1regex "mul\\((\\d+),(\\d+)\\)"
I started poking at doing a proper lexer/parser, but then I thought about how early in AoC it is and how low the chance is that the second part will require proper parsing.
So therefore; hello regex my old friend, I’ve come to talk with you again.
C#
List<string> instructions = new List<string>(); public void Input(IEnumerable<string> lines) { foreach (var line in lines) instructions.AddRange(Regex.Matches(line, @"mul\(\d+,\d+\)|do\(\)|don't\(\)").Select(m => m.Value)); } public void Part1() { var sum = instructions.Select(mul => Regex.Match(mul, @"(\d+),(\d+)").Groups.Values.Skip(1).Select(g => int.Parse(g.Value))).Select(cc => cc.Aggregate(1, (acc, val) => acc * val)).Sum(); Console.WriteLine($"Sum: {sum}"); } public void Part2() { bool enabled = true; long sum = 0; foreach(var inst in instructions) { if (inst.StartsWith("don't")) enabled = false; else if (inst.StartsWith("do")) enabled = true; else if (enabled) sum += Regex.Match(inst, @"(\d+),(\d+)").Groups.Values.Skip(1).Select(g => int.Parse(g.Value)).Aggregate(1, (acc, val) => acc * val); } Console.WriteLine($"Sum: {sum}"); }
Rust with nom parser
Decided to give it a go with the nom parser (first time using this crate). Turned out quite nicely. Had some issues with the alt combinator: All alternatives have to return the same type, using a enum to wrap all options did the trick.
use memmap2::Mmap; use nom::{ branch::alt, bytes::complete::*, character::complete::*, combinator::map, multi::many_till, sequence::tuple, AsBytes, IResult, }; #[derive(Debug)] enum Token { Do, Dont, Mul(u64, u64), } fn main() -> anyhow::Result<()> { let file = std::fs::File::open("input.txt")?; let mmap = unsafe { Mmap::map(&file)? }; let mut sum_part1 = 0; let mut sum_part2 = 0; let mut enabled = true; let mut cursor = mmap.as_bytes(); while let Ok(token) = parse(cursor) { match token.1 .1 { Token::Do => enabled = true, Token::Dont => enabled = false, Token::Mul(left, right) => { let prod = left * right; sum_part1 += prod; if enabled { sum_part2 += prod; } } } cursor = token.0; } println!("part1: {} part2: {}", sum_part1, sum_part2); Ok(()) } type ParseResult<'a> = Result<(&'a [u8], (Vec<char>, Token)), nom::Err<nom::error::Error<&'a [u8]>>>; fn parse(input: &[u8]) -> ParseResult { many_till( anychar, alt(( map(doit, |_| Token::Do), map(dont, |_| Token::Dont), map(mul, |el| Token::Mul(el.2, el.4)), )), )(input) } fn doit(input: &[u8]) -> IResult<&[u8], &[u8]> { tag("do()")(input) } fn dont(input: &[u8]) -> IResult<&[u8], &[u8]> { tag("don't()")(input) } type ParsedMulResult<'a> = (&'a [u8], &'a [u8], u64, &'a [u8], u64, &'a [u8]); fn mul(input: &[u8]) -> IResult<&[u8], ParsedMulResult> { tuple((tag("mul"), tag("("), u64, tag(","), u64, tag(")")))(input) }
Uiua
Uses (abuses?) experimental features of
fold
to track the running state of do/don’t state. Although it works well and fast, I don’t think I would recommend this code to anyone :-) Try it if you must!# Experimental! DataP₁ ← $ xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) DataP₂ ← $ xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) GetMul ← $ mul\((\d{1,3}),(\d{1,3})\) GetMulDoDont ← $ mul\(\d{1,3},\d{1,3}\)|do\(\)|don\'t\(\) &p/+≡(/×≡⋕↘1)regex GetMul DataP₁ # Part 1 # Build an accumulator to track running state of do/don't Filter ← ≡⋕↘1◌∧(⍣("0" °"n"|"1" °"("|.◌)) :"1"∵◇⊡2 regex GetMulDoDont DataP₂ ▽⊸≡(¬≍"do()"°□⊢)▽⊸Filter # Apply Filter, remove the spare 'do's &p/+≡(/×≡⋕↘1⊢regexGetMul°□⊢) # Get the digits and multiply, sum.
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))
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
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 }
You can avoid having to escape the backslashes in regexps by using multiline strings:
val pattern = """mul\((\d{1,3}),(\d{1,3})\)""".toRegex()
Rust
Regex made this one pretty straightforward. The second part additionally looks for
do()
anddon't()
in the same regex, then we do a case distinction on the match.use regex::{Regex, Captures}; fn mul_cap(cap: Captures) -> i32 { let a = cap.get(1).unwrap().as_str().parse::<i32>().unwrap(); let b = cap.get(2).unwrap().as_str().parse::<i32>().unwrap(); a * b } fn part1(input: String) { let re = Regex::new(r"mul\((\d{1,3}),(\d{1,3})\)").unwrap(); let res = re.captures_iter(&input).map(mul_cap).sum::<i32>(); println!("{res}"); } fn part2(input: String) { let re = Regex::new(r"do\(\)|don't\(\)|mul\((\d{1,3}),(\d{1,3})\)").unwrap(); let mut enabled = true; let mut res = 0; for cap in re.captures_iter(&input) { match cap.get(0).unwrap().as_str() { "do()" => enabled = true, "don't()" => enabled = false, _ if enabled => res += mul_cap(cap), _ => {} } } println!("{res}"); } util::aoc_main!();