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

  • Zarlin@lemmy.world
    link
    fedilink
    arrow-up
    0
    ·
    2 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
      0
      ·
      edit-2
      2 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.

  • lwhjp@lemmy.sdf.org
    link
    fedilink
    arrow-up
    0
    ·
    2 months 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
      0
      ·
      2 months 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?

      • mschwennesen@discuss.tchncs.de
        link
        fedilink
        arrow-up
        0
        ·
        2 months 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.

      • kintrix@linux.community
        link
        fedilink
        English
        arrow-up
        0
        ·
        edit-2
        2 months ago

        <$> is just fmap as an infix operator.

        >>> fmap (+1) [1,2,3]
        [2,3,4]
        >>> (+1) <\$> [1,2,3]
        [2,3,4]
        
  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    2 months 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
    $ 1 2 7 8 9
    $ 9 7 6 2 1
    $ 1 3 2 4 5
    $ 8 6 4 4 1
    $ 1 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?
    
    • Leavingoldhabits@lemmy.world
      link
      fedilink
      arrow-up
      0
      ·
      2 months ago

      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?

        • popcar2@programming.dev
          link
          fedilink
          arrow-up
          0
          ·
          2 months 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

      • mykl@lemmy.world
        link
        fedilink
        arrow-up
        0
        ·
        2 months 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.

  • Nighed@feddit.uk
    link
    fedilink
    English
    arrow-up
    0
    ·
    edit-2
    2 months ago

    #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;
    }
    

    }

    `

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

  • LeixB@lemmy.world
    link
    fedilink
    arrow-up
    0
    ·
    2 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)
    
  • Reptorian@programming.dev
    link
    fedilink
    arrow-up
    0
    ·
    edit-2
    2 months ago

    G’MIC solution

    spoiler
    it day2
    crop. 0,0,0,{h#-1-2}
    split. -,{_'\n'}
    foreach { replace_str. " ",";" ({t}) rm.. }
    
    safe_0,safe_1=0
    foreach {
    	({h}) a[-2,-1] y
    	num_of_attempts:=da_size(#-1)+1
    	store temp
    
    	repeat $num_of_attempts {
    
    		$temp
    
    		if $> eval da_remove(#-1,$>-1) fi
    
    		eval "
    			safe=1;
    			i[#-1,1]>i[#-1,0]?(
    				for(p=1,p<da_size(#-1),++p,
    					if(!inrange(i[#-1,p]-i[#-1,p-1],1,3,1,1),safe=0;break(););
    				);
    			):(
    				for(p=1,p<da_size(#-1),++p,
    					if(!inrange(i[#-1,p-1]-i[#-1,p],1,3,1,1),safe=0;break(););
    				);
    			);
    			safe;"
    
    		rm
    
    		if $>
    			if ${} safe_1+=1 break fi
    		else
    			if ${} safe_0,safe_1+=1 break fi
    		fi
    
    	}
    
    }
    
    echo Day" "2:" "${safe_0}" :: "${safe_1}
    
  • wer2@lemm.ee
    link
    fedilink
    arrow-up
    0
    ·
    2 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))))
    
    
  • Hammerheart@programming.dev
    link
    fedilink
    arrow-up
    0
    ·
    2 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)
    
  • Gobbel2000@programming.dev
    link
    fedilink
    English
    arrow-up
    0
    ·
    2 months 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!();
    
    • Sleepless One@lemmy.ml
      link
      fedilink
      English
      arrow-up
      0
      ·
      2 months 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.

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

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

  • Ananace@lemmy.ananace.dev
    link
    fedilink
    arrow-up
    0
    ·
    2 months 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));
    }