We're going to solve an advent of code puzzle in Roc lang. These are the functions you can use: ``` Bool.false : Bool Bool.true : Bool Decode.fromBytesPartial : List U8, fmt -> DecodeResult val where val implements Decoding, fmt implements DecoderFormatting Dict.empty : {} -> Dict * * Dict.fromList : List (k, v) -> Dict k v Dict.get : Dict k v, k -> Result v [KeyNotFound] Dict.insert : Dict k v, k, v -> Dict k v Dict.insertAll : Dict k v, Dict k v -> Dict k v Dict.joinMap : Dict a b, (a, b -> Dict x y) -> Dict x y Dict.keys : Dict k v -> List k Dict.map : Dict k a, (k, a -> b) -> Dict k b Dict.remove : Dict k v, k -> Dict k v Dict.single : k, v -> Dict k v Dict.toList : Dict k v -> List (k, v) Dict.update : Dict k v, k, (Result v [Missing] -> Result v [Missing]) -> Dict k v Dict.walk : Dict k v, state, (state, k, v -> state) -> state Encode.toBytes : val, fmt -> List U8 where val implements Encoding, fmt implements EncoderFormatting List.all : List a, (a -> Bool) -> Bool List.any : List a, (a -> Bool) -> Bool List.append : List a, a -> List a List.chunksOf : List a, U64 -> List (List a) List.concat : List a, List a -> List a List.contains : List a, a -> Bool where a implements Eq List.dropAt : List elem, U64 -> List elem List.dropFirst : List elem, U64 -> List elem List.dropIf : List a, (a -> Bool) -> List a List.dropLast : List elem, U64 -> List elem List.findFirst : List elem, (elem -> Bool) -> Result elem [NotFound] List.findFirstIndex : List elem, (elem -> Bool) -> Result U64 [NotFound] List.findLastIndex : List elem, (elem -> Bool) -> Result U64 [NotFound] List.first : List a -> Result a [ListWasEmpty] List.get : List a, U64 -> Result a [OutOfBounds] List.intersperse : List elem, elem -> List elem List.isEmpty : List * -> Bool List.join : List (List a) -> List a List.joinMap : List a, (a -> List b) -> List b List.keepIf : List a, (a -> Bool) -> List a List.keepOks : List before, (before -> Result after *) -> List after List.last : List a -> Result a [ListWasEmpty] List.len : List * -> U64 List.map : List a, (a -> b) -> List b List.map2 : List a, List b, (a, b -> c) -> List c List.mapTry : List elem, (elem -> Result ok err) -> Result (List ok) err List.mapWithIndex : List a, (a, U64 -> b) -> List b List.max : List (Num a) -> Result (Num a) [ListWasEmpty] List.min : List (Num a) -> Result (Num a) [ListWasEmpty] List.range List.repeat : a, U64 -> List a List.replace : List a, U64, a -> { list : List a, value : a } List.reverse : List a -> List a List.sortAsc : List (Num a) -> List (Num a) List.sortDesc : List (Num a) -> List (Num a) List.sortWith : List a, (a, a -> [LT, EQ, GT]) -> List a List.splitAt : List elem, U64 -> { before : List elem, others : List elem } List.splitOn : List a, a -> List (List a) where a implements Eq List.sublist : List elem, { start : U64, len : U64 } -> List elem List.sum : List (Num a) -> Num a List.takeFirst : List elem, U64 -> List elem List.takeLast : List elem, U64 -> List elem List.update : List a, U64, (a -> a) -> List a List.walk : List elem, state, (state, elem -> state) -> state List.walkBackwards : List elem, state, (state, elem -> state) -> state List.walkTry : List elem, state, (state, elem -> Result state err) -> Result state err List.walkUntil : List elem, state, (state, elem -> [Continue state, Break state]) -> state List.walkWithIndex : List elem, state, (state, elem, U64 -> state) -> state List.walkWithIndexUntil : List elem, state, (state, elem, U64 -> [Continue state, Break state]) -> state List.withCapacity : U64 -> List * Num.abs : Num a -> Num a Num.add : Num a, Num a -> Num a Num.addChecked : Num a, Num a -> Result (Num a) [Overflow] Num.bitwiseAnd : Int a, Int a -> Int a Num.bitwiseOr : Int a, Int a -> Int a Num.ceiling : Frac * -> Int * Num.compare : Num a, Num a -> [LT, EQ, GT] Num.cos : Frac a -> Frac a Num.div : Frac a, Frac a -> Frac a Num.divTrunc : Int a, Int a -> Int a Num.divTruncChecked : Int a, Int a -> Result (Int a) [DivByZero] Num.e : Frac * Num.intCast : Int a -> Int b Num.isApproxEq : Frac a, Frac a, { rtol ? Frac a, atol ? Frac a } -> Bool Num.isEven : Int a -> Bool Num.isMultipleOf : Int a, Int a -> Bool Num.max : Num a, Num a -> Num a Num.maxU64 : U64 Num.min : Num a, Num a -> Num a Num.mul : Num a, Num a -> Num a Num.pow : Frac a, Frac a -> Frac a Num.powInt : Int a, Int a -> Int a Num.rem : Int a, Int a -> Int a Num.round : Frac * -> Int * Num.shiftLeftBy : Int a, U8 -> Int a Num.shiftRightZfBy : Int a, U8 -> Int a Num.sin : Frac a -> Frac a Num.sqrt : Frac a -> Frac a Num.subChecked : Num a, Num a -> Result (Num a) [Overflow] Num.subSaturated : Num a, Num a -> Num a Num.toF64 : Num * -> F64 Num.toFrac : Num * -> Frac * Num.toI64 : Int * -> I64 Num.toI8 : Int * -> I8 Num.toStr : Num * -> Str Num.toU16 : Int * -> U16 Num.toU32 : Int * -> U32 Num.toU64 : Int * -> U64 Num.toU64Checked : Int * -> Result U64 [OutOfBounds] Num.toU8 : Int * -> U8 Result.isOk : Result ok err -> Bool Result.mapErr : Result ok a, (a -> b) -> Result ok b Result.onErr : Result a err, (err -> Result a otherErr) -> Result a otherErr Result.try : Result a err, (a -> Result b err) -> Result b err Result.withDefault : Result ok err, ok -> ok Result.map : Result a err, (a -> b) -> Result b err Result.map2 : Result a err, Result b err, (a, b -> c) -> Result c err Set.contains : Set k, k -> Bool Set.empty : {} -> Set * Set.fromList : List k -> Set k Set.insert : Set k, k -> Set k Set.intersection : Set k, Set k -> Set k Set.isEmpty : Set * -> Bool Set.keepIf : Set k, (k -> Bool) -> Set k Set.len : Set * -> U64 Set.map : Set a, (a -> b) -> Set b Set.remove : Set k, k -> Set k Set.single : k -> Set k Set.toList : Set k -> List k Set.union : Set k, Set k -> Set k Set.walkUntil : Set k, state, (state, k -> [Continue state, Break state]) -> state Str.contains : Str, Str -> Bool Str.endsWith : Str, Str -> Bool Str.fromUtf8 : List U8 -> Result Str [BadUtf8 Utf8ByteProblem U64] Str.isEmpty : Str -> Bool Str.joinWith : List Str, Str -> Str Str.repeat : Str, U64 -> Str Str.replaceEach : Str, Str, Str -> Str Str.replaceFirst : Str, Str, Str -> Str Str.splitFirst : Str, Str -> Result { before : Str, after : Str } [NotFound] Str.splitOn : Str, Str -> List Str Str.startsWith : Str, Str -> Bool Str.toI16 : Str -> Result I16 [InvalidNumStr] Str.toI64 : Str -> Result I64 [InvalidNumStr] Str.toU32 : Str -> Result U32 [InvalidNumStr] Str.toU64 : Str -> Result U64 [InvalidNumStr] Str.toUtf8 : Str -> List U8 Str.trim : Str -> Str Str.trimEnd : Str -> Str Task.map : Task a c, (a -> b) -> Task b c ``` Some examples of previous advent of code puzzles from 2023: # 1 ## Puzzle --- Day 1: Trebuchet?! --- Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems. You've been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! You try to ask why they can't just use a weather machine ("not powerful enough") and where they're even sending you ("the sky") and why your map looks mostly blank ("you sure ask a lot of questions") and hang on did you just say the sky ("of course, where do you think snow comes from") when you realize that the Elves are already loading you into a trebuchet ("please hold still, we need to strap you in"). As they're making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document. The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number. For example: 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142. Consider your entire calibration document. What is the sum of all of the calibration values? ## Solution ```roc app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br", aoc: "https://github.com/lukewilliamboswell/aoc-template/releases/download/0.2.0/tlS1ZkwSKSB87_3poSOXcwHyySe0WxWOWQbPmp7rxBw.tar.br", } import pf.Stdin import pf.Stdout import pf.Utc import aoc.AoC { stdin: Stdin.readToEnd, stdout: Stdout.write, time: \{} -> Utc.now {} |> Task.map Utc.toMillisSinceEpoch, } main = AoC.solve { year: 2023, day: 1, title: "Trebuchet?!", part1, part2, } exampleInputPart1 = """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet """ exampleInputPart2 = """ two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen """ part1 : Str -> Result Str [NotImplemented, Error Str] part1 = \input -> vals = input |> Str.splitOn "\n" |> List.map Str.toUtf8 |> List.map \bytes -> bytes |> List.keepIf isDigit |> List.map toCalibration Ok "The sum of all of the calibration values $(vals |> List.sum |> Num.toStr)" expect part1 exampleInputPart1 == Ok "The sum of all of the calibration values 142" part2 : Str -> Result Str [NotImplemented, Error Str] part2 = \input -> sum = input |> Str.splitOn "\n" |> List.map Str.toUtf8 |> List.map \bytes -> takeDigits { digits: [], rest: bytes } |> List.map toCalibration |> List.sum Ok "The sum of all of the calibration values $(Num.toStr sum)" expect part2 exampleInputPart2 == Ok "The sum of all of the calibration values 281" isDigit : U8 -> Bool isDigit = \b -> b >= '0' && b <= '9' toCalibration : List U8 -> U32 toCalibration = \digits -> when (List.first digits, List.last digits) is (Ok first, Ok last) -> when [first, last] |> Str.fromUtf8 |> Result.try Str.toU32 is Ok n -> n Err _ -> crash "couldnt parse number" _ -> crash "expected at least one number" takeDigits : { digits : List U8, rest : List U8 } -> List U8 takeDigits = \{ digits, rest } -> when rest is [] -> digits [a, ..] if isDigit a -> takeDigits { digits: List.append digits a, rest: List.dropFirst rest 1 } ['o', 'n', 'e', ..] -> takeDigits { digits: List.append digits '1', rest: List.dropFirst rest 1 } ['t', 'w', 'o', ..] -> takeDigits { digits: List.append digits '2', rest: List.dropFirst rest 1 } ['t', 'h', 'r', 'e', 'e', ..] -> takeDigits { digits: List.append digits '3', rest: List.dropFirst rest 1 } ['f', 'o', 'u', 'r', ..] -> takeDigits { digits: List.append digits '4', rest: List.dropFirst rest 1 } ['f', 'i', 'v', 'e', ..] -> takeDigits { digits: List.append digits '5', rest: List.dropFirst rest 1 } ['s', 'i', 'x', ..] -> takeDigits { digits: List.append digits '6', rest: List.dropFirst rest 1 } ['s', 'e', 'v', 'e', 'n', ..] -> takeDigits { digits: List.append digits '7', rest: List.dropFirst rest 1 } ['e', 'i', 'g', 'h', 't', ..] -> takeDigits { digits: List.append digits '8', rest: List.dropFirst rest 1 } ['n', 'i', 'n', 'e', ..] -> takeDigits { digits: List.append digits '9', rest: List.dropFirst rest 1 } _ -> takeDigits { digits, rest: List.dropFirst rest 1 } ``` # 2 ## Puzzle --- Day 3: Gear Ratios --- You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside. It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving. "Aaah!" You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help. The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing. The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently any number adjacent to a symbol, even diagonally, is a "part number" and should be included in your sum. (Periods (.) do not count as a symbol.) Here is an example engine schematic: 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361. Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic? ## Solution ```roc app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br", aoc: "https://github.com/lukewilliamboswell/aoc-template/releases/download/0.2.0/tlS1ZkwSKSB87_3poSOXcwHyySe0WxWOWQbPmp7rxBw.tar.br", } import pf.Stdin import pf.Stdout import pf.Utc import aoc.AoC { stdin: Stdin.readToEnd, stdout: Stdout.write, time: \{} -> Utc.now {} |> Task.map Utc.toMillisSinceEpoch, } main = AoC.solve { year: 2023, day: 3, title: "Gear Ratios", part1, part2, } exampleInput = """ 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. """ Location : { row : U64, col : U64 } Token : [Digit U8, Dot, Symbol [Asterisk, Slash, Equal, Ampersand, At, Plus, Hash, Minus, Dollar, Percent], Number U64] LocationToken : { loc : Location, token : Token} Schematic : Dict Location Token part1 : Str -> Result Str [NotImplemented, Error Str] part1 = \input -> inputSchematic : Schematic inputSchematic = input |> parseLocationTokens |> filterDots |> toSchematic |> replaceDigitsWithNumbers sum = inputSchematic |> symbolLocations |> List.map (adjacentLocations inputSchematic) |> List.map filterUniqueNumbers |> List.map sumPartNumbers # assume each number can only see 1 symbol, otherwise we will double count |> List.sum Ok "The sum of all of the part numbers in the engine schematic is $(Num.toStr sum)" expect part1 exampleInput == Ok "The sum of all of the part numbers in the engine schematic is 4361" part2 : Str -> Result Str [NotImplemented, Error Str] part2 = \input -> inputSchematic : Schematic inputSchematic = input |> parseLocationTokens |> filterDots |> toSchematic |> replaceDigitsWithNumbers sum = inputSchematic |> gearLocations |> List.map (adjacentLocations inputSchematic) |> List.map filterUniqueNumbers |> List.keepIf \lts -> hasExactlyTwoParts lts [] |> List.map calculateGearRatio |> List.sum Ok "The the sum of all of the gear ratios in the engine schematic is $(Num.toStr sum)" expect part2 exampleInput == Ok "The the sum of all of the gear ratios in the engine schematic is 467835" parseLocationTokens : Str -> List (List LocationToken) parseLocationTokens = \input -> input |> Str.splitOn "\n" |> List.mapWithIndex \rowStr, row -> rowStr |> Str.toUtf8 |> List.mapWithIndex \byte, col -> {loc : {row, col}, token: tokenFromByte byte } tokenFromByte : U8 -> Token tokenFromByte = \b -> when b is a if a >= '0' && a <= '9' -> Digit (a - '0') '*' -> Symbol Asterisk '/' -> Symbol Slash '=' -> Symbol Equal '&' -> Symbol Ampersand '@' -> Symbol At '#' -> Symbol Hash '+' -> Symbol Plus '-' -> Symbol Minus '$' -> Symbol Dollar '%' -> Symbol Percent '.' -> Dot _ -> str = [b] |> Str.fromUtf8 |> Result.withDefault "" crash "token '$(str)' not recognised " expect tokenFromByte '.' == Dot expect tokenFromByte '2' == Digit 2u8 expect tokenFromByte '$' == Symbol Dollar isDot : {token : Token}a -> Bool isDot = \{token} -> token != Dot expect !(isDot {loc: {row: 0, col: 0}, token: Dot}) expect isDot {loc: {row: 0, col: 0}, token: Digit 0} filterDots : List (List LocationToken) -> List LocationToken filterDots = \lts -> lts |> List.join |> List.keepIf isDot toSchematic : List LocationToken -> Schematic toSchematic = \lts -> List.walk lts (Dict.empty {}) \dict, lt -> Dict.insert dict lt.loc lt.token symbolLocations : Schematic -> List Location symbolLocations = \schematic -> Dict.walk schematic [] \acc, loc, token -> when token is Symbol _ -> List.append acc loc _ -> acc # increasing row is down # increasing col is right move : Location -> ([UpLeft, UpRight, DownLeft, DownRight, Left, Up, Right, Down] -> Result Location [Invalid]) move = \{row, col} -> \direction -> maybeRow = when direction is UpLeft -> Num.subChecked row 1 UpRight -> Num.subChecked row 1 DownLeft -> Num.addChecked row 1 DownRight -> Num.addChecked row 1 Left -> Ok row Up -> Num.subChecked row 1 Right -> Ok row Down -> Num.addChecked row 1 maybeCol = when direction is UpLeft -> Num.subChecked col 1 UpRight -> Num.addChecked col 1 DownLeft -> Num.subChecked col 1 DownRight -> Num.addChecked col 1 Left -> Num.subChecked col 1 Up -> Ok col Right -> Num.addChecked col 1 Down -> Ok col when (maybeRow, maybeCol) is (Ok r, Ok c) -> Ok {row: r, col: c} _ -> Err Invalid getToken : Schematic -> (Location -> Result LocationToken [NothingAtLocation]) getToken = \schematic -> \loc -> when Dict.get schematic loc is Ok token -> Ok {loc, token} Err KeyNotFound -> Err NothingAtLocation adjacentLocations : Schematic -> (Location -> List LocationToken) adjacentLocations = \schematic -> \curr -> [UpLeft,UpRight,DownLeft,DownRight,Left,Up,Right,Down] |> List.keepOks (move curr) |> List.keepOks (getToken schematic) # take a schematic and convert any digits into the number at that location replaceDigitsWithNumbers : Schematic -> Schematic replaceDigitsWithNumbers = \schematic -> Dict.map schematic \loc, token -> when token is Digit _ -> Number (getNumberAtLocation schematic loc WalkingLeft) _ -> token # start with a digit, walk left to first digit, then walk right building up the number getNumberAtLocation : Schematic, Location, [WalkingLeft, BuildingNumber U64] -> U64 getNumberAtLocation = \schematic, loc, state -> maybeRight = (move loc) Right |> Result.try \right -> when Dict.get schematic right is Ok (Digit u8) -> Ok (right, u8) _ -> Err Invalid maybeLeft = (move loc) Left |> Result.try \left -> when Dict.get schematic left is Ok (Digit u8) -> Ok (left, u8) _ -> Err Invalid maybeCurrent = when Dict.get schematic loc is Ok (Digit u8) -> Ok (loc, u8) _ -> Err Invalid when (state, maybeLeft, maybeRight, maybeCurrent ) is (WalkingLeft, Ok (left, _), _, Ok _ ) -> getNumberAtLocation schematic left WalkingLeft (WalkingLeft, _, _, Err _ ) -> crash "starting location isn't a digit or isn't in schematic" (WalkingLeft, _, Ok (right, _), Ok (_, u8) ) -> getNumberAtLocation schematic right (BuildingNumber (Num.toU64 u8)) (WalkingLeft, _, _, Ok (_, u8) ) -> Num.toU64 u8 # single number (WalkingLeft, _, _, _ ) -> crash "unable to move right" (BuildingNumber u64, _, Ok (right, _), Ok (_, u8) ) -> getNumberAtLocation schematic right (BuildingNumber ((u64 * 10) + (Num.toU64 u8))) (BuildingNumber u64, _, _, Ok (_, u8) ) -> (u64 * 10) + (Num.toU64 u8) # base case (BuildingNumber _, _, _, _ ) -> crash "moved to a location that isnt a number" # take a list of location/tolen pairs and keep only unique numbers filterUniqueNumbers : List LocationToken -> List LocationToken filterUniqueNumbers = \lts -> filterUniqueNumbersHelp lts [] [] filterUniqueNumbersHelp : List LocationToken, List U64, List LocationToken -> List LocationToken filterUniqueNumbersHelp = \lts, seen, keep -> next = List.dropFirst lts 1 when lts is [] -> keep # base case, keep these locations [first, ..] -> when first.token is Number u64 if !(List.contains seen u64) -> # we haven't seen this number before filterUniqueNumbersHelp next (List.append seen u64) (List.append keep first) _ -> filterUniqueNumbersHelp next seen keep # ignore anything that is not a number sumPartNumbers : List LocationToken -> U64 sumPartNumbers = \lts -> next = List.dropFirst lts 1 when lts is [] -> 0 # base case [first, ..] -> when first.token is Number u64 -> u64 + (sumPartNumbers next) # next _ -> crash "expected only numbers" gearLocations : Schematic -> List Location gearLocations = \schematic -> Dict.walk schematic [] \acc, loc, token -> when token is Symbol Asterisk -> List.append acc loc _ -> acc hasExactlyTwoParts : List LocationToken, List U64 -> Bool hasExactlyTwoParts = \lts, seen -> next = List.dropFirst lts 1 when lts is [] -> List.len seen == 2 [first, .. ] -> when first.token is Number u64 -> hasExactlyTwoParts next (List.append seen u64) _ -> crash "expect only numbers" calculateGearRatio : List LocationToken -> U64 calculateGearRatio = \lts -> expect List.len lts <= 2 next = List.dropFirst lts 1 when lts is [] -> 1 # base case [first, ..] -> when first.token is Number u64 -> u64 * (calculateGearRatio next) # next _ -> crash "expected only numbers" ``` We're now going to solve the first puzzle for advent of code 2024. ## Puzzle --- Day 3: Mull It Over --- "Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?" The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. For example, consider the following section of corrupted memory: xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? --- Part Two --- As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. There are two new instructions you'll need to handle: The do() instruction enables future mul instructions. The don't() instruction disables future mul instructions. Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. For example: xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. This time, the sum of the results is 48 (2*4 + 8*5). Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications? ## Solution ```roc app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.17.0/lZFLstMUCUvd5bjnnpYromZJXkQUrdhbva4xdBInicE.tar.br", aoc: "https://github.com/lukewilliamboswell/aoc-template/releases/download/0.2.0/tlS1ZkwSKSB87_3poSOXcwHyySe0WxWOWQbPmp7rxBw.tar.br", } import pf.Stdin import pf.Stdout import pf.Utc import aoc.AoC { stdin: Stdin.readToEnd, stdout: Stdout.write, time: \{} -> Utc.now {} |> Task.map Utc.toMillisSinceEpoch, } main = AoC.solve { year: 2024, day: 3, title: "Mull It Over", part1, part2, } exampleInput = """ xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) """ part1 : Str -> Result Str [NotImplemented, Error Str] part1 = \input -> sum = input |> Str.toUtf8 |> scanMultiplications [] |> List.sum Ok "The sum of all multiplications is $(Num.toStr sum)" part2 : Str -> Result Str [NotImplemented, Error Str] part2 = \_ -> Err NotImplemented # Walk byte by byte looking for 'mul' followed by proper pattern scanMultiplications : List U8, List U64 -> List U64 scanMultiplications = \bytes, results -> when bytes is [] -> results ['m', 'u', 'l', '(', ..] -> # Found potential multiplication, extract the numbers rest = List.dropFirst bytes 4 when extractNumbers rest is Ok { first, second, remaining } -> scanMultiplications remaining (List.append results (first * second)) Err _ -> scanMultiplications (List.dropFirst bytes 1) results [_, ..] -> scanMultiplications (List.dropFirst bytes 1) results # Returns the two numbers and remaining bytes if valid mul instruction found extractNumbers : List U8 -> Result { first: U64, second: U64, remaining: List U8 } [InvalidFormat] extractNumbers = \bytes -> when extractFirstNumber bytes is Ok { number: first, remaining } -> when remaining is [',', ..] -> remainingAfterComma = List.dropFirst remaining 1 when extractFirstNumber remainingAfterComma is Ok { number: second, remaining: final } -> when final is [')', ..] -> Ok { first, second, remaining: List.dropFirst final 1, } _ -> Err InvalidFormat _ -> Err InvalidFormat _ -> Err InvalidFormat _ -> Err InvalidFormat # Extract a valid 1-3 digit number from the start of the bytes extractFirstNumber : List U8 -> Result { number: U64, remaining: List U8 } [InvalidFormat] extractFirstNumber = \bytes -> digits = bytes |> List.walkUntil [] \acc, byte -> if isDigit byte then when List.len acc is len if len >= 3 -> Break acc _ -> Continue (List.append acc byte) else Break acc when digits is [] -> Err InvalidFormat _ -> when digits |> Str.fromUtf8 |> Result.try Str.toU64 is Ok num -> Ok { number: num, remaining: List.dropFirst bytes (List.len digits), } Err _ -> Err InvalidFormat isDigit : U8 -> Bool isDigit = \byte -> byte >= '0' && byte <= '9' expect result = part1 exampleInput result == Ok "The sum of all multiplications is 161" expect bytes = [',', '4', '5', ')'] |> extractFirstNumber bytes == Err InvalidFormat expect bytes = ['4', '5', ','] |> extractFirstNumber bytes == Ok { number: 45, remaining: [','] } expect bytes = ['4', '5', '6', '7'] |> extractFirstNumber bytes == Ok { number: 456, remaining: ['7'] } expect bytes = ['a'] |> extractFirstNumber bytes == Err InvalidFormat ``` Complete the rest of the solution. Extra instructions: - If the user provides you with an error, start your reply with an analysis of what could be going wrong paired with potential solutions. There is no need to provide an explanation after the code block. - Always reply with the full code, no partial snippets with changes. - Do not use the Parser package. - String interpolation works like this: `"Two plus three is: $(Num.toStr (2 + 3))"`. - Use intermediary variables in your expect tests, all variables will be printed on failure, that will make debugging easier. Example: ``` expect part1Result = part1 exampleInput part1Result == Ok "The sum is 161" ``` - You can use `dbg` for debugging, `dbg` does not work with intermediary variables like `expect`. Examples: ``` # standalone version dbg count # expression version if sum == 1 then dbg singular else plural ``` - Make sure to properly format variables of multiline strings. Example: ``` exampleInputPart1 = """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet """ ```