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
    link
    13 hours 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).