Day 2: Red-Nosed Reports
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://blocks.programming.dev/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/22323136
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Smalltalk
Discovered a number of frustrations with this supposedly small and elegant language
- Smalltalk’s block based iteration has NO control flow
- blocks are very dissimilar to functions
- You cannot early return from blocks (leading to a lot of horrible nested ifs or boolean operations)
- Smalltalk’s messages (~functions) cannot take multiple arguments, instead it has these sort of combined messages, so instead of a function with three arguments, you would send 3 combined messages with one argument. This is fine until you try to chain messages with arguments, as smalltalk will interpret them as a combined message and fail, forcing you to either break into lots of temp variables, or do lisp-like parenthesis nesting, both of which I hate
- Smalltalk’s order of operations, while nice and simple, is also quite frustrating at times, similar to #4, forcing you to break into lots of temp variables, or do lisp-like parenthesis nesting. For instance
(nums at: i) - (nums at: i+1)
which would benums[i] - nums[i+1]
in most languages
Part 1
day2p1: input ^ (input lines collect: [ :l | l substrings collect: [ :s | s asInteger ]]) count: [ :nums | (nums = nums sorted or: nums = nums sorted reverse) and: [ (1 to: nums size-1) allSatisfy: [ :i | ((nums at: i) - (nums at: i+1)) abs between: 1 and: 3 ] ] ]
Part 2
day2p2: input | temp | ^ (input lines collect: [ :l | (l substrings collect: [ :s | s asInteger ]) asOrderedCollection ]) count: [ :nums | (self day2p2helper: nums) or: [ ((1 to: nums size) anySatisfy: [ :i | temp := nums copy. temp removeAt: i. self day2p2helper: temp ]) or: [(self day2p2helper: nums reversed) or: [ (1 to: nums size) anySatisfy: [ :i | temp := nums reversed. temp removeAt: i. self day2p2helper: temp ] ]]] . ]
day2p2helper: nums ^ (1 to: nums size - 1) allSatisfy: [ :i | ((nums at: i+1) - (nums at: i)) between: 1 and: 3 ].
#Zig
const std = @import("std"); const List = std.ArrayList; const splitScalar = std.mem.splitScalar; const parseInt = std.fmt.parseInt; const print = std.debug.print; const concat = std.mem.concat; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = gpa.allocator(); const Answer = struct { safe: u32, tolerated: u32, }; pub fn isSafe(levels: []i32) bool { if (levels.len == 0) { return false; } // slide window in pairs, advancing by one var it = std.mem.window(i32, levels, 2, 1); const first = it.first(); const decreasing = first[0] - first[1] > 0; it.reset(); // rewind the iterator while (it.next()) |slice| { const lhs: i32 = slice[0]; const rhs: i32 = slice[1]; if (decreasing) { if (lhs <= rhs) return false; if (lhs - rhs < 1 or lhs - rhs > 3) return false; } else { if (rhs <= lhs) return false; if (rhs - lhs < 1 or rhs - lhs > 3) return false; } } return true; } pub fn solve(input: []const u8) !Answer { var rows = splitScalar(u8, input, '\n'); // PART 1 // determine how many reports are safe var safe_reports: u32 = 0; var tolerated_reports: u32 = 0; var unsafe_reports = List([]i32).init(alloc); defer unsafe_reports.deinit(); while (rows.next()) |row| { var levels = splitScalar(u8, row, ' '); var report = List(i32).init(alloc); defer report.deinit(); while (levels.next()) |level| { const value = parseInt(i32, level, 10) catch continue; report.append(value) catch continue; } if (isSafe(report.items)) { safe_reports += 1; } else { try unsafe_reports.append(try alloc.dupe(i32, report.items)); } } // PART 2 // determine how many unsafe reports can be tolerated for (unsafe_reports.items) |report| { var index: usize = 0; while (index < report.len) : (index += 1) { // mutate report by removing one level const mutated_report = concat( alloc, i32, &[_][]const i32{ report[0..index], report[index + 1 ..] }, ) catch report; defer alloc.free(mutated_report); if (isSafe(mutated_report)) { tolerated_reports += 1; break; } } } return Answer{ .safe = safe_reports, .tolerated = safe_reports + tolerated_reports }; } pub fn main() !void { const answer = try solve(@embedFile("input.txt")); print("Part 1: {d}\n", .{answer.safe}); print("Part 2: {d}\n", .{answer.tolerated}); } test "test input" { const answer = try solve(@embedFile("test.txt")); try std.testing.expectEqual(2, answer.safe); try std.testing.expectEqual(4, answer.tolerated);
Kotlin:
import kotlin.math.abs import kotlin.math.sign data class Report(val levels: List<Int>) { fun isSafe(withProblemDampener: Boolean): Boolean { var orderSign = 0.0f // - 1 is descending; +1 is ascending levels.zipWithNext().forEachIndexed { index, level -> val difference = (level.second - level.first).toFloat() if (orderSign == 0.0f) orderSign = sign(difference) if (sign(difference) != orderSign || abs(difference) !in 1.0..3.0) { // With problem dampener: Drop either element in the pair or the first element from the original list and check if the result is now safe. return if (withProblemDampener) { Report(levels.drop(1)).isSafe(false) || Report(levels.withoutElementAt(index)).isSafe(false) || Report(levels.withoutElementAt(index + 1)).isSafe(false) } else false } } return true } } fun main() { fun part1(input: List<String>): Int = input.map { Report(it.split(" ").map { it.toInt() }).isSafe(false) }.count { it } fun part2(input: List<String>): Int = input.map { Report(it.split(" ").map { it.toInt() }).isSafe(true) }.count { it } // Or read a large test input from the `src/Day01_test.txt` file: val testInput = readInput("Day02_test") check(part1(testInput) == 2) check(part2(testInput) == 4) // Read the input from the `src/Day01.txt` file. val input = readInput("Day02") part1(input).println() part2(input).println() }
The Report#isSafe method essentially solves both parts.
I’ve had a bit of a trip up in part 2:
I initially only checked, if the report was safe, if either elements in the pair were to be removed. But in the edge case, that the first pair has different monotonic behaviour than the rest, the issue would only be detected by the second pair with indices (2, 3), whilst removing the first element in the list would yield a safe report.
Factor
: get-input ( -- reports ) "vocab:aoc-2024/02/input.txt" utf8 file-lines [ split-words [ string>number ] map ] map ; : slanted? ( report -- ? ) { [ [ > ] monotonic? ] [ [ < ] monotonic? ] } || ; : gradual? ( report -- ? ) [ - abs 1 3 between? ] monotonic? ; : safe? ( report -- ? ) { [ slanted? ] [ gradual? ] } && ; : part1 ( -- n ) get-input [ safe? ] count ; : fuzzy-reports ( report -- reports ) dup length <iota> [ remove-nth-of ] with map ; : tolerable? ( report -- ? ) { [ safe? ] [ fuzzy-reports [ safe? ] any? ] } || ; : part2 ( -- n ) get-input [ tolerable? ] count ;
Quite the interesting language choice. It’s so clean. I love it!
def is_safe(report: list[int]) -> bool: global removed acceptable_range = [_ for _ in range(-3,4) if _ != 0] diffs = [] if any([report.count(x) > 2 for x in report]): return False for i, num in enumerate(report[:-1]): cur = num next = report[i+1] difference = cur - next diffs.append(difference) if difference not in acceptable_range: return False if len(diffs) > 1: if diffs[-1] * diffs[-2] <= 0: return False return True with open('input') as reports: list_of_reports = reports.readlines()[:-1] count = 0 failed_first_pass = [] failed_twice = [] for reportsub in list_of_reports: levels = [int(l) for l in reportsub.split()] original = levels.copy() if is_safe(levels): safe = True count += 1 else: failed_first_pass.append(levels) for report in failed_first_pass: print(report) working_copy = report.copy() for i in range(len(report)): safe = False working_copy.pop(i) print("checking", working_copy) if is_safe(working_copy): count += 1 safe = True break else: working_copy = report.copy() print(count)
this took me so fucking long and in the end i just went for brute force anyway. there are still remnants of some of previous, overly complicated, failed attempts, like the hideous
global removed
. In the end, I realized I was fucking up by using remove() instead of pop(), it was causing cases with duplicates where the removal of one would yield a safe result to count as unsafe.
Elixir
defmodule Day02 do defp part1(reports) do reports |> Enum.map(fn report -> levels = report |> String.split() |> Enum.map(&String.to_integer/1) cond do sequence_is_safe?(levels) -> :safe true -> :unsafe end end) |> Enum.count(fn x -> x == :safe end) end defp part2(reports) do reports |> Enum.map(fn report -> levels = report |> String.split() |> Enum.map(&String.to_integer/1) sequences = 0..(length(levels) - 1) |> Enum.map(fn i -> List.delete_at(levels, i) end) cond do sequence_is_safe?(levels) -> :safe Enum.any?(sequences, &sequence_is_safe?/1) -> :safe true -> :unsafe end end) |> Enum.count(fn x -> x == :safe end) end defp all_gaps_within_max_diff?(numbers) do numbers |> Enum.chunk_every(2, 1, :discard) |> Enum.all?(fn [a, b] -> abs(b - a) <= 3 end) end defp is_strictly_increasing?(numbers) do numbers |> Enum.chunk_every(2, 1, :discard) |> Enum.all?(fn [a, b] -> a < b end) end defp is_strictly_decreasing?(numbers) do numbers |> Enum.chunk_every(2, 1, :discard) |> Enum.all?(fn [a, b] -> a > b end) end defp sequence_is_safe?(numbers) do (is_strictly_increasing?(numbers) or is_strictly_decreasing?(numbers)) and all_gaps_within_max_diff?(numbers) end def run(data) do reports = data |> String.split("\n", trim: true) p1 = part1(reports) p2 = part2(reports) IO.puts(p1) IO.puts(p2) end end data = File.read!("input.in") Day02.run(data)
Kotlin
A bit late to the party, but here you go.
import kotlin.math.abs fun part1(input: String): Int { return solve(input, ::isSafe) } fun part2(input: String): Int { return solve(input, ::isDampSafe) } private fun solve(input: String, condition: (List<Int>) -> Boolean): Int { var safeCount = 0 input.lines().forEach { line -> if (line.isNotBlank()) { val nums = line.split("\\s+".toRegex()).map { it.toInt() } safeCount += if (condition(nums)) 1 else 0 } } return safeCount } private fun isSafe(list: List<Int>): Boolean { val safeDiffs = setOf(1, 2, 3) var incCount = 0 var decCount = 0 for (idx in 0..<list.lastIndex) { if (!safeDiffs.contains(abs(list[idx] - list[idx + 1]))) { return false } if (list[idx] <= list[idx + 1]) incCount++ if (list[idx] >= list[idx + 1]) decCount++ } return incCount == 0 || decCount == 0 } private fun isDampSafe(list: List<Int>): Boolean { if (isSafe(list)) { return true } else { for (idx in 0..list.lastIndex) { val shortened = list.toMutableList() shortened.removeAt(idx) if (isSafe(shortened)) { return true } } } return false }
#Rust
initially, for part two I was trying to ignore a bad pair not a bad value - read the question!
Only installed Rust on Sunday, day 1 was a mess, today was more controlled. Need to look at some of the rust solutions for std library methods I don’t know about.
very focussed on getting it to actually compile/work over making it short or nice!
long!
`
pub mod task_2 {
pub fn task_1(input: &str) -> i32{ let mut valid_count = 0; let reports = process_input(input); for report in reports{ let valid = is_report_valid(report); if valid{ valid_count += 1; } } println!("Valid count: {}", valid_count); valid_count } pub fn task_2(input: &str) -> i32{ let mut valid_count = 0; let reports = process_input(input); for report in reports{ let mut valid = is_report_valid(report.clone()); if !valid { for position_to_delete in 0..report.len() { let mut updated_report = report.clone(); updated_report.remove(position_to_delete); valid = is_report_valid(updated_report); if valid { break; } } } if valid{ valid_count += 1; } } println!("Valid count: {}", valid_count); valid_count } fn is_report_valid(report:Vec<i32>) -> bool{ let mut increasing = false; let mut decreasing = false; let mut valid = true; for position in 1..report.len(){ if report[position-1] > report[position] { decreasing = true; } else if report[position-1] < report[position] { increasing = true; } else { valid = false; break; } if (report[position-1] - report[position]).abs() > 3 { valid = false; break; } if increasing && decreasing { valid = false; break; } } return valid; } pub fn process_input(input: &str) -> Vec<Vec<i32>>{ let mut reports: Vec<Vec<i32>> = Vec::new(); for report_string in input.split("\n"){ let mut report: Vec<i32> = Vec::new(); for value in report_string.split_whitespace() { report.push(value.parse::<i32>().unwrap()); } reports.push(report); } return reports; }
}
`
Lisp
Part 1
(defun p1-process-line (line) (mapcar #'parse-integer (str:words line))) (defun line-direction-p (line) "make sure the line always goes in the same direction" (loop for x in line for y in (cdr line) count (> x y) into dec count (< x y) into inc when (and (> dec 0 ) (> inc 0)) return nil when (= x y) return nil finally (return t))) (defun line-in-range-p (line) "makes sure the delta is within 3" (loop for x in line for y in (cdr line) for delta = (abs (- x y)) when (or (> delta 3) ) return nil finally (return t))) (defun test-line-p (line) (and (line-in-range-p line) (line-direction-p line))) (defun run-p1 (file) (let ((data (read-file file #'p1-process-line))) (apply #'+ (mapcar (lambda (line) (if (test-line-p line) 1 0)) data))))
Part 2
(defun test-line-p2 (line) (or (test-line-p (cdr line)) (test-line-p (cdr (reverse line))) (loop for back on line collect (car back) into front when (test-line-p (concatenate 'list front (cddr back))) return t finally (return nil) ))) (defun run-p2 (file) (let ((data (read-file file #'p1-process-line))) (loop for line in data count (test-line-p2 line))))
Haskell
This was quite fun! I got a bit distracted trying to rewrite
safe
in point-free style, but I think this version is the most readable. There’s probably a more monadic way of writinglessOne
as well, but I can’t immediately see it.safe xs = any gradual [diffs, negate <$> diffs] where diffs = zipWith (-) (drop 1 xs) xs gradual = all (`elem` [1 .. 3]) lessOne [] = [] lessOne (x : xs) = xs : map (x :) (lessOne xs) main = do input :: [[Int]] <- map (map read . words) . lines <$> readFile "input02" print . length $ filter safe input print . length $ filter (any safe . lessOne) input
Love to see your haskell solutions!
I am so far very amazed with the compactness of your solutions, your
lessOne
is very much mind-Bending. I have never used or seen<$>
before, is it a monadic?
Also I can’t seem to find your logic for this safety condition:
The levels are either all increasing or all decreasing
, did you figure that it wasn’t necessary?For the last point, it isn’t needed since the differences between elements should be all positive or all negative for the report to be safe. This is tested with the combination of
negate
andgradual
.I am also enjoying these Haskell solutions. I’m still learning the language, so it’s been cool to compare my solution with these and grow my understanding of Haskell.
Thanks! The other two posters already answered your questions, I think :)
Haskell makes it really easy to build complex operations out of simple functional building blocks, skipping a lot of boilerplate needed in some other languages. I find the compactness easier to read, but I realize that not everyone would agree.
BTW, I’m a relative Haskell newbie. I’m sure more experienced folks could come up with even more interesting solutions!
<$>
is justfmap
as an infix operator.>>> fmap (+1) [1,2,3] [2,3,4] >>> (+1) <\$> [1,2,3] [2,3,4]
JavaScript
Also wrote a solution in JavaScript to play around with list comprehension. Wrote some utility functions for expressiveness (and lazy evaluation).
Code
const fs = require("fs"); const U = require("./util"); const isSafe = xs => U.pairwise(xs).every(([a,b]) => a!==b && a-b > -4 && a-b < 4) && new Set(U.pairwise(xs).map(([a,b]) => a < b)).size === 1; const rows = fs .readFileSync(process.argv[2] || process.stdin.fd, "utf8") .split("\n") .filter(x => x != "") .map(x => x.split(/ +/).map(Number)); const p1 = U.countBy(rows, isSafe); const p2 = U.countBy(rows, row => isSafe(row) || U.someBy(U.indices(row), i => isSafe([...row.slice(0, i), ...row.slice(i+1)]))); console.log("02:", p1, p2);
https://github.com/sjmulder/aoc/blob/master/2024/js/day02.js
Rust
The function is_sorted_by on Iterators turned out helpful for compactly finding if a report is safe. In part 2 I simply tried the same with each element removed, since all reports are very short.
fn parse(input: String) -> Vec<Vec<i32>> { input.lines() .map(|l| l.split_whitespace().map(|w| w.parse().unwrap()).collect()) .collect() } fn is_safe(report: impl DoubleEndedIterator<Item=i32> + Clone) -> bool { let safety = |a: &i32, b: &i32| (1..=3).contains(&(b - a)); report.clone().is_sorted_by(safety) || report.rev().is_sorted_by(safety) } fn part1(input: String) { let reports = parse(input); let safe = reports.iter().filter(|r| is_safe(r.iter().copied())).count(); println!("{safe}"); } fn is_safe2(report: &[i32]) -> bool { (0..report.len()).any(|i| { // Try with each element removed is_safe(report.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, n)| *n)) }) } fn part2(input: String) { let reports = parse(input); let safe = reports.iter().filter(|r| is_safe2(r)).count(); println!("{safe}"); } util::aoc_main!();
is_sorted_by
is new to me, could be very useful.The
is_sorted_by
is a really nice approach. I originally tried using that function thinking that|a, b| a > b
or|a, b| a < b
would cut it but it didn’t end up working. I never thought to handle the check for the step being between 1 and 3 in the callback closure for that though.
This is my very naive rust solution, part 2 is mostly just an extra function, so they’re bother covered in this one.
C#
using MathNet.Numerics.LinearAlgebra; public class Day02 : Solver { private ImmutableList<Vector<Double>> data; public void Presolve(string input) { data = input.Trim().Split("\n") .Select( line => Vector<Double>.Build.DenseOfEnumerable(line.Split(' ').Select(double.Parse)) ).ToImmutableList(); } private bool IsReportSafe(Vector<Double> report) { Vector<Double> delta = report.SubVector(1, report.Count - 1) .Subtract(report.SubVector(0, report.Count - 1)); return (delta.ForAll(x => x > 0) || delta.ForAll(x => x < 0)) && Vector<Double>.Abs(delta).Max() <= 3; } private bool IsDampenedReportSafe(Vector<Double> report) { for (Double i = 0; i < report.Count; ++i) { var dampened = Vector<Double>.Build.DenseOfEnumerable( report.EnumerateIndexed() .Where(item => item.Item1 != i) .Select(item => item.Item2)); if (IsReportSafe(dampened)) return true; } return false; } public string SolveFirst() => data.Where(IsReportSafe).Count().ToString(); public string SolveSecond() => data.Where(IsDampenedReportSafe).Count().ToString(); }
Uiua
Uiua is still developing very quickly, and this code uses the experimental
tuples
function, hence the initial directive.# Experimental! "7 6 4 2 1\n1 2 7 8 9\n9 7 6 2 1\n1 3 2 4 5\n8 6 4 4 1\n1 3 6 7 9" ⊜(⊜⋕⊸≠@\s)⊸≠@\n # Partition at \n, then at space, parse ints. IsSorted ← +⊃(≍⇌⍆.|≍⍆.) # Compare with sorted array. IsSmall ← /××⊃(>0|<4)⌵↘¯1-↻1. # Copy offset by 1, check diffs. IsSafe ← ×⊃IsSmall IsSorted # Safe if Small steps and Ordered. IsSafer ← ±/+≡IsSafe ⧅<-1⧻. # Choose 4 from 5, check again. &p/+≡IsSafe . # Part1 : Is each row safe? &p/+≡(±+⊃IsSafe IsSafer) # Part2 : Is it safe or safer?
How do you write this, not conceptually but physically. Do you have a char picker open at all times?
Haha, you can do it that way, in fact the online Uiua Pad editor has all the operators listed along the top.
But all the operators have ascii names, so you can type e.g.
IsSmall = reduce mul mul fork(>0|<4) abs drop neg 1 - rot 1 dup
and the formatter will reduce that toIsSmall ← /××⊃(>0|<4)⌵↘¯1-↻1.
whenever you save or execute code.That works in the Pad, and you can enable similar functionality in other editors.
i can only imagine doing it with a drawing tablet
I like to assume people using array programming languages just have a crystal ball that they use to call upon magic runes on the screen
This looks so alien! Does it work with the full set? The comment says 5, choose 4, but I guess it’s written as n, choose n-1?
Yes, it should do. I do run the solutions against the live data, but sometimes tweak the solutions afterwards, so can’t always guarantee them :-). I left the comment as 5 choose 4 as it felt clearer in the context of the test data.
It does still feel very alien at times, but I do love being able to think about how to adopt a more arrays-based approach to solving these problems.