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
    2
    ·
    25 days 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
      25 days 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.