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

  • Andy@programming.dev
    cake
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    6 months ago

    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 ;
    
  • sjmulder@lemmy.sdf.org
    link
    fedilink
    arrow-up
    2
    ·
    6 months ago

    C

    First went through the input in one pass, number by number, but unfortunately that wouldn’t fly for part 2.

    Code
    #include "common.h"
    
    static int
    issafe(int *lvs, int n, int skip)
    {
    	int safe=1, asc=0,prev=0, ns=0,i;
    
    	for (i=0; safe && i<n; i++) {
    		if (i == skip)
    			{ ns = 1; continue; }
    		if (i-ns > 0)
    			safe = safe && lvs[i] != prev &&
    			    lvs[i] > prev-4 && lvs[i] < prev+4;
    		if (i-ns == 1)
    			asc = lvs[i] > prev;
    		if (i-ns > 1)
    			safe = safe && (lvs[i] > prev) == asc;
    
    		prev = lvs[i];
    	}
    
    	return safe;
    }
    
    int
    main(int argc, const char **argv)
    {
    	char buf[64], *rest, *tok;
    	int p1=0,p2=0, lvs[16],n=0, i;
    
    	if (argc > 1)
    		DISCARD(freopen(argv[1], "r", stdin));
    
    	while ((rest = fgets(buf, sizeof(buf), stdin))) {
    		for (n=0; (tok = strsep(&rest, " ")); n++) {
    			assert(n < (int)LEN(lvs));
    			lvs[n] = (int)strtol(tok, NULL, 10);
    		}
    
    		for (i=-1; i<n; i++)
    			if (issafe(lvs, n, i))
    				{ p1 += i == -1; p2++; break; }
    	}
    
    	printf("02: %d %d\n", p1, p2);
    }
    

    https://github.com/sjmulder/aoc/blob/master/2024/c/day02.c

    • Faresh@lemmy.ml
      link
      fedilink
      English
      arrow-up
      1
      ·
      6 months ago

      What is this coding style? The function type, name and open brace placement made me think GNU at first, but the code in the body doesn’t look like GCS at all.

  • sjmulder@lemmy.sdf.org
    link
    fedilink
    arrow-up
    2
    ·
    6 months ago

    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

  • wer2@lemm.ee
    link
    fedilink
    arrow-up
    2
    ·
    6 months ago

    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))))
    
    
  • VegOwOtenks@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    6 months ago

    Haskell

    runningDifference :: [Int] -> [Int]
    runningDifference (a:[]) = []
    runningDifference (a:b:cs) = a - b : (runningDifference (b:cs))
    
    isSafe :: [Int] -> Bool
    isSafe ds = (all (> 0) ds || all (< 0) ds) && (all (flip elem [1, 2, 3] . abs) ds) 
    
    isSafe2 :: [Int] -> Bool
    isSafe2 ds = any (isSafe2') (zip [0..length ds] (cycle [ds]))
    
    isSafe2' (i, ls) = isSafe . runningDifference $ list
            where
                    list = dropIndex i ls
    
    dropIndex _ []     = []
    dropIndex 0 (a:as) = dropIndex (-1) as
    dropIndex i (a:as) = a : dropIndex (i - 1) as
    
    main = do
            c <- getContents
            let reports = init . lines $ c
            let levels  = map (map read . words) reports :: [[Int]]
            let differences = map runningDifference levels
            let safety = map isSafe differences
            let safety2 = map isSafe2 levels
    
            putStrLn . show . length . filter (id) $ safety
            putStrLn . show . length . filter (id) $ safety2
    
            return ()
    

    Took me way too long to figure out that I didn’t have to drop one of them differences but the initial Number

  • ystael@beehaw.org
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    J

    There is probably a way to write this more point-free. You can definitely see here the friction involved in the way J wants to regard lists as arrays: short rows of the input matrix are zero padded, so you have to snip off the padding before you process each row, and that means you can’t lift some of the operations back up to the parent matrix because it will re-introduce the padding as it reshapes the result; this accounts for a lot of the "1 everywhere (you can interpret v"1 as “force the verb v to operate on rank 1 subarrays of the argument”).

    data_file_name =: '2.data'
    data =: > 0 ". each cutopen toJ fread data_file_name
    
    NB. {. take, i. index of; this removes trailing zeros
    remove_padding =: {.~ i.&amp;0
    
    NB. }. behead, }: curtail; this computes successive differences
    diff =: }. - }:
    
    NB. a b in_range y == a &lt;: y &lt;: b
    in_range =: 4 : '(((0 { x) &amp; &lt;:) * (&lt;: &amp; (1 { x))) y'
    
    NB. a row is safe if either all successive differences are in [1..3] or all in [_3.._1]
    NB. +. or
    ranges =: 2 2 $ 1 3 _3 _1
    row_safe =: (+./"1) @: (*/"1) @: (ranges &amp; (in_range"1 _)) @: diff @: remove_padding
    
    result1 =: +/ safe"1 data
    
    NB. x delete y is y without the xth element
    delete =: 4 : '(x {. y) , ((>: x) }. y)'"0 _
    modified_row =: 3 : 'y , (i.#y) delete y'
    
    modified_row_safe =: 3 : '+./"1 row_safe"1 modified_row"1 y'
    result2 =: +/ modified_row_safe data
    
  • the_beber@lemm.ee
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    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.

  • Hammerheart@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago
    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)
    
    • Hammerheart@programming.dev
      link
      fedilink
      arrow-up
      1
      ·
      6 months ago

      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.

  • proved_unglue@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    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
    }
    
  • Rin@lemm.ee
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    TypeScript

    Solution
    import { AdventOfCodeSolutionFunction } from "./solutions";
    
    
    /**
     * this function evaluates the 
     * @param levels a list to check
     * @returns -1 if there is no errors, or the index of where there's an unsafe event
     */
    export function EvaluateLineSafe(levels: Array<number>) {
        // this loop is the checking every number in the line
        let isIncreasing: boolean | null = null;
        for (let levelIndex = 1; levelIndex < levels.length; levelIndex++) {
            const prevLevel = levels[levelIndex - 1]; // previous
            const level = levels[levelIndex]; // current
            const diff = level - prevLevel; // difference
            const absDiff = Math.abs(diff); // absolute difference
    
            // check if increasing too much or not at all
            if (absDiff == 0 || absDiff > 3)
                return levelIndex; // go to the next report
    
            // set increasing if needed
            if (isIncreasing === null) {
                isIncreasing = diff > 0;
                continue; // compare the next numbers
            }
    
            //  check if increasing then decreasing 
            if (!(isIncreasing && diff > 0 || !isIncreasing && diff < 0))
                return levelIndex; // go to the next report
        }
    
        return -1;
    }
    
    
    export const solution_2: AdventOfCodeSolutionFunction = (input) => {
        const reports = input.split("\n");
    
        let safe = 0;
        let safe_damp = 0;
    
        // this loop is for every line
        main: for (let i = 0; i < reports.length; i++) {
            const report = reports[i].trim();
            if (!report)
                continue; // report is empty
    
            const levels = report.split(" ").map((v) => Number(v));
    
            const evaluation = EvaluateLineSafe(levels);
            if(evaluation == -1) {
                safe++;
                continue;
            }
            
            // search around where it failed
            for (let offset = evaluation - 2; offset <= evaluation + 2; offset++) {
                // delete an evaluation in accordance to the offset
                let newLevels = [...levels];
                newLevels.splice(offset, 1);
                const newEval = EvaluateLineSafe(newLevels);
                if(newEval == -1) {
                    safe_damp++;
                    continue main;
                }
            }
        }
    
        return `Part 1: ${safe} Part 2: ${safe + safe_damp}`;
    }
    

    God, I really wish my solutions weren’t so convoluted. Also, this is an O(N^3) solution…

    • hades@lemm.ee
      link
      fedilink
      arrow-up
      3
      ·
      6 months ago

      I don’t think your solution is O(N^3). Can you explain your reasoning?

        • hades@lemm.ee
          link
          fedilink
          arrow-up
          2
          ·
          6 months ago

          It’s not as simple as that. You can have 20 nested for loops with complexity of O(1) if all of them only ever finish one iteration.

          Or you can have one for loop that iterates 2^N times.

          • Rin@lemm.ee
            link
            fedilink
            arrow-up
            1
            ·
            6 months ago

            What do you think my complexity is?

            I think it could be maybe O(n^2) because the other for loop which tries elements around the first error will only execute a constant of 5 times in the worst case? I’m unsure.

            • hades@lemm.ee
              link
              fedilink
              arrow-up
              3
              ·
              6 months ago

              It’s O(n).

              If you look at each of the levels of all reports, you will access it a constant number of times: at most twice in each call to EvaluateLineSafe, and you will call EvaluateLineSafe at most six times for each report.

            • Gobbel2000@programming.dev
              link
              fedilink
              arrow-up
              3
              arrow-down
              1
              ·
              6 months ago

              It really depends on what your parameter n is. If the only relevant size is the number of records (let’s say that is n), then this solution takes time in O(n), because it loops over records only once at a time. This ignores the length of records by considering it constant.

              If we also consider the maximum length of records (let’s call it m), then your solution, and most others I’ve seen in this thread, has a time complexity in O(n * m^2) for part 2.

  • LeixB@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    Haskell

    Had some fun with arrows.

    import Control.Arrow
    import Control.Monad
    
    main = getContents >>= print . (part1 &&& part2) . fmap (fmap read . words) . lines
    
    part1 = length . filter isSafe
    part2 = length . filter (any isSafe . removeOne)
    
    isSafe = ap (zipWith (-)) tail >>> (all (between 1 3) &&& all (between (-3) (-1))) >>> uncurry (||)
     where
      between a b = (a <=) &&& (<= b) >>> uncurry (&&)
    
    removeOne [] = []
    removeOne (x : xs) = xs : fmap (x :) (removeOne xs)
    
  • TunaCowboy@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    edit-2
    6 months ago

    python

    solution
    import re
    import aoc
    
    def setup():
        return (aoc.get_lines(2), 0)
    
    def safe(data):
        order = 0 if data[0] < data[1] else 1
        for i in range(0, len(data) - 1):
            h = data[i]
            t = data[i + 1]
            d = abs(h - t)
            if d not in [1, 2, 3] or (order == 0 and h >= t) or (
                    order == 1 and h <= t):
                return False
        return True
    
    def one():
        lines, acc = setup()
        for l in lines:
            if safe([int(x) for x in re.findall(r'\d+', l)]):
                acc += 1
        print(acc)
    
    def two():
        lines, acc = setup()
        for l in lines:
            data = [int(x) for x in re.findall(r'\d+', l)]
            for i in range(len(data)):
                if safe(data[:i] + data[i + 1:]):
                    acc += 1
                    break
        print(acc)
    
    one()
    two()
    
  • antlion@lemmy.dbzer0.com
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    R (R-Wasm)

    input = file('input2024day2.txt',open='r')
    lines = readLines(input)
    library(stringr)
    safe = 0
    safe2 = 0
    for (ln in lines){
      vals = as.numeric(unlist(str_split(ln,' ')))
      diffs = diff(vals)
      cond1 = min(diffs) > 0 || max(diffs) < 0
      cond2 = max(abs(diffs)) < 4
      if (cond1 && cond2){
        safe = safe + 1
      }
      else { #Problem Dampener
        dampen = FALSE
        for (omit in -1:-length(vals)){
          diffs = diff(vals[omit])
          cond1 = min(diffs) > 0 || max(diffs) < 0
          cond2 = max(abs(diffs)) < 4
          if (cond1 && cond2){
            dampen = TRUE
          }
        }
        if (dampen){
          safe2 = safe2 + 1}
      }
    }
    print (safe) #Part 1
    print (safe + safe2) #Part 2
    
  • Zarlin@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    Nim

    import strutils, times, sequtils, sugar
    
    # check if level transition in record is safe
    proc isSafe*(sign:bool, d:int): bool =
      sign == (d>0) and d.abs in 1..3;
    
    #check if record is valid
    proc validate*(record:seq[int]): bool =
      let sign = record[0] > record[1];
      return (0..record.len-2).allIt(isSafe(sign, record[it] - record[it+1]))
    
    # check if record is valid as-is
    # or if removing any item makes the record valid
    proc validate2*(record:seq[int]): bool =
      return record.validate or (0..<record.len).anyIt(record.dup(delete(it)).validate)
    
    proc solve*(input:string): array[2,int] =
      let lines = input.readFile.strip.splitLines;
      let records = lines.mapIt(it.splitWhitespace.map(parseInt));
      result[0] = records.countIt(it.validate);
      result[1] = records.countIt(it.validate2);
    

    I got stuck on part 2 trying to check everything inside a single loop, which kept getting more ugly. So then I switched to just deleting one item at a time and re-checking the record.

    Reworked it after first finding the solution to compress the code a bit, though the range iterators don’t really help with readability.

    I did learn about the sugar import, which I used to make the sequence duplication more compact: record.dup(delete(it).

    • janAkali@lemmy.one
      link
      fedilink
      English
      arrow-up
      2
      ·
      edit-2
      6 months ago

      Cool to see another solution in Nim here =)

      (0..<record.len).anyIt(record.dup(delete(it)).validate)

      That’s smart. I haven’t thought of using iterators to loop over indexes (except in a for loop).

      I got stuck on part 2 trying to check everything inside a single loop, which kept getting more ugly.

      Yeah I’ve thought of simple ways to do this and found none. And looking at the input - it’s too easy to bruteforce, especially in compiled lang like Nim.

  • bugsmith@programming.dev
    link
    fedilink
    arrow-up
    1
    ·
    6 months ago

    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)