this post was submitted on 02 Dec 2024
44 points (97.8% liked)

Advent Of Code

913 readers
95 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 18 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

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

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 2 points 1 day ago (1 children)

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).

[โ€“] [email protected] 2 points 1 day ago* (last edited 1 day 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.