/* 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 Compared to 3.pi, this an alternative (and a little neater) version of part2/0. part1/0 is the same. 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 3b.pi Time (mean ± σ): 37.3 ms ± 8.2 ms [User: 22.7 ms, System: 14.4 ms] Range (min … max): 14.6 ms … 49.9 ms 64 runs */ go => part1, part2, nl. /* Hyperfine Benchmark 1: picat -g part1 3b.pi Time (mean ± σ): 37.8 ms ± 5.7 ms [User: 19.7 ms, System: 17.6 ms] Range (min … max): 23.9 ms … 48.9 ms 60 runs */ part1 => println(find_all_mul(read_file_chars("3.txt")).sum). /* Hyperfine Benchmark 1: picat -g part2 3b.pi Time (mean ± σ): 37.1 ms ± 6.6 ms [User: 20.7 ms, System: 15.9 ms] Range (min … max): 18.8 ms … 50.0 ms 67 runs */ parse2([],Status,Mul) = [Status,Mul]. parse2(L,true,Mul0) = [Status,Mul] => ( append(Valid,"don't()",Rest,L) -> Mul1 = find_all_mul(Valid), [Status,Mul] = parse2(Rest,false,Mul1++Mul0) ; Mul1 = find_all_mul(L), [Status,Mul] = parse2("",true,Mul1++Mul0) ). parse2(L,false,Mul0) = [Status,Mul] => ( append(_A,"do()",Rest,L) -> [Status,Mul] = parse2(Rest,true,Mul0) ; [Status,Mul] = parse2("",false,Mul0) ). part2 => File = "3.txt", Lines = read_file_lines(File), Sum = 0, Status = true, foreach(Line in Lines) [Status1,Mul] = parse2(Line,Status,[]), Status := Status1, Sum := Sum + Mul.sum 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)].