/* Advent of Code 2024 in Picat. Problem 3 https://adventofcode.com/2024/day/3 Note: This program uses my regex module: https://github.com/hakank/picat_regex This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import regex. import aoc_utils. main => go. /* Hyperfine Benchmark 1: picat -g go 3.pi Time (mean ± σ): 40.7 ms ± 5.8 ms [User: 22.9 ms, System: 17.8 ms] Range (min … max): 29.1 ms … 51.3 ms 60 runs */ go => part1, part2, nl. /* Hyperfine Benchmark 1: picat -g part1 3.pi Time (mean ± σ): 39.3 ms ± 5.8 ms [User: 20.9 ms, System: 18.3 ms] Range (min … max): 23.8 ms … 49.9 ms 61 runs */ part1 => println(find_all_mul(read_file_chars("3.txt")).sum). /* Hyperfine Benchmark 1: picat -g part2 3.pi Time (mean ± σ): 37.6 ms ± 5.9 ms [User: 23.5 ms, System: 14.1 ms] Range (min … max): 24.2 ms … 49.9 ms 55 runs See 3b.pi for a little neater version, though with the same general idea of using append/4. */ part2 => File = "3.txt", Lines = read_file_lines(File), Sum = 0, Enable = true, foreach(Line in Lines) L=copy_term(Line), S = 0, while(L.len > 0) if Enable then if append(Valid,"don't()",Rest,L) then Found = find_all_mul(Valid), S := S + Found.sum, Enable := false, L := Rest else Found = find_all_mul(L), S := S + Found.sum, Enable := true, L := "" end else if append(A,"do()",Rest,L) then L := Rest, Enable := true else L := "", Enable := false end end end, Sum := Sum + S end, println(Sum), nl. % Using regex find_all_mul(L) = [A.to_int*B.to_int : [A,B] in regex_find_all("mul\\((\\d+?),(\\d+?)\\)",L)].