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
Uiua
Regex my beloved <3
Run with example input here
FindMul ← regex "mul\\((\\d+),(\\d+)\\)" PartOne ← ( &rs ∞ &fo "input-3.txt" FindMul /+≡(×°⊟⋕⊏1_2) ) IdDont ← ⊗□"don't()"♭ PartTwo ← ( &rs ∞ &fo "input-3.txt" regex "mul\\(\\d+,\\d+\\)|do\\(\\)|don't\\(\\)" ⍢(IdDont. ↘1⊃↘↙ ⊗□"do()"♭. ⊂↘1↘ | IdDont. ≠⧻, ) ▽♭=0⌕□"do()". ≡(×°⊟⋕⊏1_2♭FindMul)♭ /+ ) &p "Day 3:" &pf "Part 1: " &p PartOne &pf "Part 2: " &p PartTwo
Haskell
module Main where import Control.Arrow hiding ((+++)) import Data.Char import Data.Functor import Data.Maybe import Text.ParserCombinators.ReadP hiding (get) import Text.ParserCombinators.ReadP qualified as P data Op = Mul Int Int | Do | Dont deriving (Show) parser1 :: ReadP [(Int, Int)] parser1 = catMaybes <$> many ((Just <$> mul) <++ (P.get $> Nothing)) parser2 :: ReadP [Op] parser2 = catMaybes <$> many ((Just <$> operation) <++ (P.get $> Nothing)) mul :: ReadP (Int, Int) mul = (,) <$> (string "mul(" *> (read <$> munch1 isDigit <* char ',')) <*> (read <$> munch1 isDigit <* char ')') operation :: ReadP Op operation = (string "do()" $> Do) +++ (string "don't()" $> Dont) +++ (uncurry Mul <$> mul) foldOp :: (Bool, Int) -> Op -> (Bool, Int) foldOp (_, n) Do = (True, n) foldOp (_, n) Dont = (False, n) foldOp (True, n) (Mul a b) = (True, n + a * b) foldOp (False, n) _ = (False, n) part1 = sum . fmap (uncurry (*)) . fst . last . readP_to_S parser1 part2 = snd . foldl foldOp (True, 0) . fst . last . readP_to_S parser2 main = getContents >>= print . (part1 &&& part2)
Of course it’s point-free
Elixir
First time writing Elixir. It’s probably janky af.
I’ve had some help from AI to get some pointers along the way. I’m not competing in any way, just trying to learn and have fun.
~~Part 2 is currently not working, and I can’t figure out why. I’m trying to just remove everything from “don’t()” to “do()” and just pass the rest through the working solution for part 1. Should work, right?
Any pointers?~~
edit; working solution:
defmodule Three do def get_input do File.read!("./input.txt") end def extract_operations(input) do Regex.scan(~r/mul\((\d{1,3}),(\d{1,3})\)/, input) |> Enum.map(fn [_op, num1, num2] -> num1 = String.to_integer(num1) num2 = String.to_integer(num2) [num1 * num2] end) end def sum_products(ops) do List.flatten(ops) |> Enum.filter(fn x -> is_integer(x) end) |> Enum.sum() end def part1 do extract_operations(get_input()) |> sum_products() end def part2 do String.split(get_input(), ~r/don\'t\(\)[\s\S]*?do\(\)/) |> Enum.map(&extract_operations/1) |> sum_products() end end IO.puts("part 1: #{Three.part1()}") IO.puts("part 2: #{Three.part2()}")
Part 2 is currently not working, and I can’t figure out why. I’m trying to just remove everything from “don’t()” to “do()” and just pass the rest through the working solution for part 1. Should work, right?
I think I had the same issue. Consider what happens if there isn’t a do() after a don’t().
Ah, yes, that’s it. The lazy solution would be to add a “do()” to the end of the input, right? Haha
It was actually a line break that broke the regex. Changing from a “.” to “[\s\S]” fixed it.
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!