/* Advent of Code 2023 Day 4 in Picat. https://adventofcode.com/2023/day/4 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 'picat 4.pi' Benchmark 1: picat 4.pi Time (mean ± σ): 38.7 ms ± 6.1 ms [User: 23.1 ms, System: 15.6 ms] Range (min … max): 16.5 ms … 50.8 ms 60 runs */ go => part1_2, nl. part1_2 => File = "4.txt", Lines = read_file_lines(File), ScoresPart1 = 0, Wins = [], foreach(Line in Lines) [_Card,Nums] = Line.split(":"), [WinningS,MyNumbersS] = Nums.split("|"), Winning = WinningS.split(" "), MyNumbers = MyNumbersS.split(" "), Score = 0, foreach(Num in MyNumbers, membchk(Num,Winning)) Score := cond(Score == 0, 1, Score * 2) end, ScoresPart1 := ScoresPart1 + Score, Wins := Wins ++ [[1 : Num in MyNumbers, membchk(Num,Winning)].len] end, % Part 1 println(ScoresPart1), % Part 2 Len = Wins.len, Times = new_array(Len), bind_vars(Times,1), foreach(I in 1..Len) foreach(J in I+1..I+Wins[I], J <= Len) Times[J] := Times[J] + Times[I] end end, println(Times.sum).