1
+ # Read the input file containing the reports, each report is a line of space-separated numbers.
2
+ input = readlines (" inputs/day2" )
3
+
4
+ # Parse the input into an array of arrays, where each sub-array represents a report of integers.
5
+ reports = map (input) do x
6
+ x = split (x, " " ) # Split each line into individual strings (numbers).
7
+ x = parse .(Int, x) # Convert the strings to integers.
8
+ end
9
+
10
+ # Function to check if a report is "safe".
11
+ # A report is safe if the levels are all increasing or all decreasing
12
+ # and the difference between any two adjacent levels is between 1 and 3 inclusive.
13
+ function report_is_save (report)
14
+ delta = report[2 : end ] - report[1 : end - 1 ] # Calculate differences between adjacent levels.
15
+
16
+ # Check if all differences are either positive (increasing) or negative (decreasing).
17
+ if ! (all (delta .> 0 ) || all (delta .< 0 ))
18
+ return false # If not, the report is unsafe.
19
+ end
20
+
21
+ delta = abs .(delta) # Take the absolute value of the differences.
22
+
23
+ # Check if the maximum difference is greater than 3.
24
+ if maximum (delta) > 3
25
+ return false # If so, the report is unsafe.
26
+ end
27
+
28
+ return true # If both conditions are met, the report is safe.
29
+ end
30
+
31
+ # Calculate and print the result for Part 1: Count the number of safe reports.
32
+ println (" Result Part 1: " , report_is_save .(reports) |> sum)
33
+
34
+ # Function to check if a report can be made safe by tolerating a single "bad" level.
35
+ function is_save_tolerate_a_single (report)
36
+ # Iterate through each level in the report.
37
+ for i in eachindex (report)
38
+ xd = deleteat! (copy (report), i) # Remove the i-th level from the report.
39
+ if report_is_save (xd) # Check if the modified report is safe.
40
+ return true # If so, return true.
41
+ end
42
+ end
43
+ return false # If no single level can be removed to make it safe, return false.
44
+ end
45
+
46
+ # Calculate and print the result for Part 2: Count the number of reports that are either
47
+ # inherently safe or can be made safe by tolerating a single bad level.
48
+ println (" Result Part 2: " , is_save_tolerate_a_single .(reports) |> sum)
0 commit comments