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

  • Rin@lemm.ee
    link
    fedilink
    arrow-up
    2
    ·
    3 hours 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…

  • LeixB@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    3 hours 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)
    
  • ystael@beehaw.org
    link
    fedilink
    arrow-up
    2
    ·
    4 hours 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
    
  • Sleepless One@lemmy.ml
    link
    fedilink
    English
    arrow-up
    1
    ·
    4 hours ago

    Rust

    use crate::utils::read_lines;
    
    pub fn solution1() {
        let reports = get_reports();
        let safe_reports = reports
            .filter(|report| report.windows(3).all(window_is_valid))
            .count();
    
        println!("Number of safe reports = {safe_reports}");
    }
    
    pub fn solution2() {
        let reports = get_reports();
        let safe_reports = reports
            .filter(|report| {
                (0..report.len()).any(|i| {
                    [&report[0..i], &report[i + 1..]]
                        .concat()
                        .windows(3)
                        .all(window_is_valid)
                })
            })
            .count();
    
        println!("Number of safe reports = {safe_reports}");
    }
    
    fn window_is_valid(window: &[usize]) -> bool {
        matches!(window[0].abs_diff(window[1]), 1..=3)
            && matches!(window[1].abs_diff(window[2]), 1..=3)
            && ((window[0] > window[1] && window[1] > window[2])
                || (window[0] < window[1] && window[1] < window[2]))
    }
    
    fn get_reports() -> impl Iterator<Item = Vec<usize>> {
        read_lines("src/day2/input.txt").map(|line| {
            line.split_ascii_whitespace()
                .map(|level| {
                    level
                        .parse()
                        .expect("Reactor level is always valid integer")
                })
                .collect()
        })
    }
    

    Definitely trickier than yesterday’s. I feel like the windows solution isn’t the best, but it was what came to mind and ended up working for me.

  • Deebster
    link
    fedilink
    arrow-up
    1
    ·
    4 hours ago

    I forgot that this started yesterday, so I’m already behind. I quite like my solution for part one, but part two will have to wait.

    Rust

    use color_eyre::eyre;
    use std::{fs, num, str::FromStr};
    
    #[derive(Debug, PartialEq, Eq)]
    struct Report(Vec<isize>);
    
    impl FromStr for Report {
        type Err = num::ParseIntError;
    
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let v: Result<Vec<isize>, _> = s
                .split_whitespace()
                .map(|num| num.parse::<isize>())
                .collect();
            Ok(Report(v?))
        }
    }
    
    impl Report {
        fn is_safe(&self) -> bool {
            let ascending = self.0[1] > self.0[0];
            let (low, high) = if ascending { (1, 3) } else { (-3, -1) };
            self.0.windows(2).all(|w| {
                let a = w[0];
                let b = w[1];
                b >= a + low && b <= a + high
            })
        }
    }
    
    fn main() -> eyre::Result<()> {
        color_eyre::install()?;
    
        let part1 = part1("d02/input.txt")?;
        println!("Part 1: {part1}");
        Ok(())
    }
    
    fn part1(filepath: &str) -> eyre::Result<isize> {
        let mut num_safe = 0;
        for l in fs::read_to_string(filepath)?.lines() {
            if Report::from_str(l)?.is_safe() {
                num_safe += 1;
            }
        }
        Ok(num_safe)
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
    
        #[test]
        fn sample_part1() {
            assert_eq!(part1("test.txt").unwrap(), 2);
        }
    }
    
  • Gobbel2000
    link
    fedilink
    English
    arrow-up
    3
    ·
    7 hours ago

    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!();
    
    • Deebster
      link
      fedilink
      English
      arrow-up
      2
      ·
      4 hours ago

      is_sorted_by is new to me, could be very useful.

    • Sleepless One@lemmy.ml
      link
      fedilink
      English
      arrow-up
      1
      ·
      4 hours ago

      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.

  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    8 hours ago

    Uiua

    Uiua is still developing very quickly, and this code uses the experimental tuples function, hence the initial directive.

    Try it Live!

    # 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?
    
      • mykl@lemmy.world
        link
        fedilink
        arrow-up
        4
        ·
        6 hours ago

        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 to IsSmall ← /××⊃(>0|<4)⌵↘¯1-↻1. whenever you save or execute code.

        That works in the Pad, and you can enable similar functionality in other editors.

        • popcar2
          link
          fedilink
          arrow-up
          4
          ·
          6 hours ago

          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

  • sjmulder@lemmy.sdf.org
    link
    fedilink
    arrow-up
    3
    ·
    10 hours 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

  • Ananace@lemmy.ananace.dev
    link
    fedilink
    arrow-up
    3
    ·
    11 hours ago

    Of course I ended up with a off-by-one error for the second part, so things took a bit longer than they really should’ve.

    But either way, behold, messy C#:

    C#
    int[][] reports = new int[0][];
    
    public void Input(IEnumerable<string> lines)
    {
      reports = lines.Select(l => l.Split(' ').Select(p => int.Parse(p)).ToArray()).ToArray();
    }
    
    public void Part1()
    {
      int safeCount = reports.Where(report => CheckReport(report)).Count();
      Console.WriteLine($"Safe: {safeCount}");
    }
    public void Part2()
    {
      int safeCount = reports.Where(report => {
        if (CheckReport(report))
          return true;
    
        for (int i = 0; i < report.Length; ++i)
          if (CheckReport(report.Where((_, j) => j != i)))
            return true;
    
        return false;
      }).Count();
    
      Console.WriteLine($"Safe: {safeCount}");
    }
    
    bool CheckReport(IEnumerable<int> report)
    {
      var diffs = report.SkipLast(1).Zip(report.Skip(1)).Select(v => v.Second - v.First);
      return diffs.All(v => Math.Abs(v) <= 3) && (diffs.All(v => v > 0) || diffs.All(v => v < 0));
    }
    
  • Leo Uino@lemmy.sdf.org
    link
    fedilink
    arrow-up
    8
    ·
    14 hours ago

    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 writing lessOne 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
    
    • VegOwOtenks@lemmy.world
      link
      fedilink
      English
      arrow-up
      3
      ·
      13 hours ago

      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?

      • kintrix@linux.community
        link
        fedilink
        English
        arrow-up
        1
        ·
        edit-2
        58 minutes ago

        <$> is just fmap as an infix operator.

        >>> fmap (+1) [1,2,3]
        [2,3,4]
        >>> (+1) <\$> [1,2,3]
        [2,3,4]
        
      • mschwennesen@discuss.tchncs.de
        link
        fedilink
        arrow-up
        2
        ·
        4 hours ago

        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 and gradual.

        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.

  • janAkali@lemmy.one
    link
    fedilink
    English
    arrow-up
    4
    ·
    edit-2
    14 hours ago

    Nim

    Got correct answer for part 1 on first try, but website rejected it. Wasted some time debugging and trying different methods. Only to have the same answer accepted minutes later. =(

    proc isSafe(report: seq[int]): bool =
      let diffs = collect:
        for i, n in report.toOpenArray(1, report.high): n - report[i]
      (diffs.allIt(it > 0) or diffs.allIt(it < 0)) and diffs.allIt(it.abs in 1..3)
    
    proc solve(input: string): AOCSolution[int, int] =
      let lines = input.splitLines()
      var reports: seq[seq[int]]
      for line in lines:
        reports.add line.split(' ').map(parseInt)
    
      for report in reports:
        if report.isSafe():
          inc result.part1
          inc result.part2
        else:
          for t in 0..report.high:
            var mReport = report
            mReport.delete t
            if mReport.isSafe():
              inc result.part2
              break
    

    Codeberg repo

  • VegOwOtenks@lemmy.world
    link
    fedilink
    arrow-up
    3
    ·
    14 hours 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