Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8609

Teaching and learning resources • Re: Advent of Code 2024

$
0
0
--- Day 18: RAM Run ---

Finally decided to do one more. Day 18 is also running in a grid, but I figured out a different approach. No arrays, no indexing, no testing for out of bounds indexes!
I implemented the RAM matrix as a hashtable. Of-course, initial setup requires some indexing to set-up the hashtable, but there's no indexing after that.
Hashtable entries are for example '(0 . 0) - (that is a pair, or improper list in Scheme) as a key, and '((1 . 0) (0 . 1)) as a value - (neighbors of the '(0 . 0) key).
This of-course, slows me down (compared to arrays), but I have absolutely no indexing after that!
The path search is a very simple graph traversal (probably would qualify as DFS)

Code:

(define (run seen from to) ;; DFS - I think???  (cond   ((equal? from to) 0)   (else    (let* ((nbrs (hashtable-ref ram from #f))   (not-seen (filter (lambda (n) (not (member n seen))) nbrs))   (new-seen (append not-seen seen)))      (cond       ((null? not-seen) #f)       (else(flatten (map (lambda (nbr) (inc1 (run new-seen nbr to)))      not-seen))))))))
The slowdown here is member function that is filtering out neighbors that have been visited in the current generation of recursion. Member is O(n) function.

Code:

hrvoje@BPI-F3:~/Projects/advent-of-code/2024/day-18/Chez$ schemeChez Scheme Version 10.1.0Copyright 1984-2024 Cisco Systems, Inc.> (load "day18-part2.ss")> (time (lambda () (day18 "input.txt")))360#<time-duration 0.053240108>
I'm cheating here :D . This is on banana, but a second run, when the memoization hashtable has already been initialized. The real timing is 24.9s for the first run.

My i5 (which is a 5 year old computer) does the first run in 1.9s, so I guess it is a good enough solution.

Statistics: Posted by hrvoje064 — Fri Feb 07, 2025 4:47 pm



Viewing all articles
Browse latest Browse all 8609

Trending Articles