/* Advent of Code 2024 in Picat. Problem 2 https://adventofcode.com/2024/day/2 This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. /* Hyperfine Benchmark 1: picat -g go 2.pi Time (mean ± σ): 57.0 ms ± 7.6 ms [User: 40.8 ms, System: 16.2 ms] Range (min … max): 38.8 ms … 70.9 ms 43 runs */ go ?=> part1, part2, nl. /* Combining part1 and part2 Hyperfine Benchmark 1: picat -g go2 2.pi Time (mean ± σ): 52.0 ms ± 8.2 ms [User: 34.5 ms, System: 17.5 ms] Range (min … max): 33.2 ms … 65.4 ms 48 runs */ go2 => File = "2.txt", Lines = [Line.map(to_int): Line in read_file_lines(File).map(split)], member(Part,1..2), Safe = 0, foreach(Line in Lines) if (Part==1,safe(Line)) ; (Part==2, select(_A,Line,Line2), safe(Line2)) then Safe := Safe + 1 end end, println(Safe), Part == 2. % Force backtracking of Part /* Hyperfine Benchmark 1: picat -g part1 2.pi Time (mean ± σ): 43.8 ms ± 6.7 ms [User: 26.4 ms, System: 17.4 ms] Range (min … max): 26.9 ms … 58.1 ms 44 runs */ part1 => File = "2.txt", Lines = [Line.map(to_int): Line in read_file_lines(File).map(split)], Safe = 0, foreach(Line in Lines) if safe(Line) then Safe := Safe + 1 end end, println(Safe). /* Hyperfine Benchmark 1: picat -g part2 2.pi Time (mean ± σ): 52.4 ms ± 5.7 ms [User: 34.8 ms, System: 17.7 ms] Range (min … max): 41.0 ms … 64.5 ms 46 runs */ part2 => File = "2.txt", Lines = [Line.map(to_int): Line in read_file_lines(File).map(split)], Safe = 0, foreach(Line in Lines) if safe(Line) then Safe := Safe + 1 elseif select(_A,Line,Line2), safe(Line2) then Safe := Safe + 1 end end, println(Safe). differences(L) = [L[I]-L[I-1] : I in 2..L.len]. safe(Line) => Safe = true, S = sort(Line), Creasing = (Line == S ; Line == S.reverse), % increasing or decreasing? T = differences(S), Min = min(T), Max = max(T), if not(Creasing, Min >= 1, Max <= 3) then Safe := false end, Safe == true.