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

Teaching and learning resources • Re: Advent of Code 2023

$
0
0
The asymptotic runtime of checking all pairs is n*(n-1)/2 where n is the number of galaxies. On a grid that is M by N there could be at most n=M*N galaxies, which leads to a worst-case runtime that scales as N*M*(N*M-1)/2.

The Julia code first tallies how many galaxies are in each column and each row. It then computes the total horizontal distance between each column weighted by the galaxies in each column using at most N*(N-1)/2 operations and adds to that the total vertical distance between rows weighted by the galaxies in each row using at most M*(M-1)/2 operations.

The result is a worst case time complexity of O((N+M)²) versus O((N*M)²). Unless I missed something, it would appear the universe is so sparsely populated that either method results in reasonably fast solutions.
I just had to try this!
And while at it, I rewrote everything in pure functional style. No assignments (set!), and no arrays (vectors). My last HOP solution still had 3 vectors: grid for reading positions, and row, and column expansion vectors.
This one only uses lists, and is only 20 lines of code.
It is also much faster than any of my solutions before.
on opi5+

Code:

hrvoje@hrvoje64:~/Projects/advent-of-code/day11$ ./cosmic-expansioncpu time: 18 real time: 18 gc time: 210494813840988812853
Racket code:

Code:

#lang racket(require racket/file);;; --- Day 11: Cosmic Expansion ---(define (cosmic-expansion factor file)  (let* ((lines (map string->list (file->lines file #:mode 'text)))         (columns (apply map (lambda xs xs) lines))         (g-col (map (lambda (col) (length (filter (curry char=? #\#) col))) columns))         (g-row (map (lambda (row) (length (filter (curry char=? #\#) row))) lines)))    (+ (foldl (lambda (ps r) (+ (distance (first ps) (second ps)) r))              0 (combinations (expand factor g-row 0) 2))       (foldl (lambda (ps r) (+ (distance (first ps) (second ps)) r))              0 (combinations (expand factor g-col 0) 2)))))(define (distance d1 d2)  (* (- (car d2) (car d1)) (cdr d1) (cdr d2)))(define (expand factor rc nrc)  (cond    ((null? rc) null)    ((zero? (car rc))     (expand factor (cdr rc) (+ nrc factor)))    (else     (cons (cons nrc (car rc))           (expand factor (cdr rc) (add1 nrc))))));;; Run ==================================================================(time (values  (cosmic-expansion 2 "input.txt")  (cosmic-expansion 1000000 "input.txt")))

Statistics: Posted by hrvoje064 — Sun Jan 07, 2024 11:44 am



Viewing all articles
Browse latest Browse all 6796

Trending Articles