this post was submitted on 13 Nov 2025
3 points (63.6% liked)

Advent Of Code

1122 readers
4 users here now

An unofficial home for the advent of code community on programming.dev! Other challenges are also welcome!

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.

Everybody Codes is another collection of programming puzzles with seasonal events.

EC 2025

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 19 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 2 years ago
MODERATORS
 

Quest 8: The Art of Connection

  • 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://topaz.github.io/paste/ if you prefer sending it through a URL

Link to participate: https://everybody.codes/

top 6 comments
sorted by: hot top controversial new old
[–] vole@lemmy.world 2 points 1 day ago

Scheme/Guile

Takes about 5 seconds.

(import (rnrs io ports (6))
        (srfi srfi-1))
#!curly-infix

(define (parse-file file-name)
  (let ((sequence (map string->number (string-split (string-trim-both (call-with-input-file file-name get-string-all)) #\,))))
    (zip sequence (cdr sequence))))

(let loop ((sequence (parse-file "notes/everybody_codes_e2025_q08_p1.txt")) (count 0))
  (if (null? sequence)
      (format #t "P1 Answer: ~a\n\n" count)
      (loop (cdr sequence) (+ count (if (and last (eq? (modulo (- (cadar sequence) (caar sequence)) 32) 16)) 1 0)))))

(define (crosses-over? a b)
  (let ((a1 (car a))
        (a2 (cadr a))
        (b1 (car b))
        (b2 (cadr b)))
    (let ((a2 (modulo {a2 - a1} 256))
          (b1 (modulo {b1 - a1} 256))
          (b2 (modulo {b2 - a1} 256)))
      (and (not (eq? b1 0)) (not (eq? b2 0))
      (or
        (and {b1 < a2} {b2 > a2})
        (and {b1 > a2} {b2 < a2}))))))
(define (count-cross-overs sequence a)
  (let loop ((sequence sequence) (count 0))
    (if (null? sequence)
        count
        (loop (cdr sequence) (+ count (if (crosses-over? (car sequence) a) 1 0))))))
(let loop ((sequence (parse-file "notes/everybody_codes_e2025_q08_p2.txt")) (passed '()) (count 0))
  (if (null? sequence)
      (format #t "P2 Answer: ~a\n\n" count)
      (loop (cdr sequence) (cons (car sequence) passed) (+ count (count-cross-overs passed (car sequence))))))


(let ((sequence (parse-file "notes/everybody_codes_e2025_q08_p3.txt")))
  (let loop ((i 1) (greatest 0))
    (if {i > 256}
        (format #t "P3 Answer: ~a\n\n" greatest)
        (loop (1+ i) (max greatest (let loop ((j i) (greatest 0))
              (if {j > 256}
                  greatest
                  (loop (1+ j) (max greatest (count-cross-overs sequence (list i j)))))))))))
[–] mykl@lemmy.world 2 points 5 days ago* (last edited 5 days ago)

Uiua

Just a dirty great hack and a few minutes of toasty CPU for part3 with live data.

"1,5,2,6,8,4,1,7,3"
βŠœβ‹•βŠΈβ‰ @,
&p /+=βŠƒ(β§ˆβ‚‚(⌡/-)|Γ·2/β†₯) # Part1 --> 4

"1,5,2,6,8,4,1,7,3,5,7,8,2"
βŠœβ‹•βŠΈβ‰ @,
Knot  ← (βŠƒ(=Β―|=)∩⌞(Β±-)βŠ™Β°βŠŸ)
Knots ← /↧/β†₯β†―βˆž_2[∩⌟Knot]°⊟
β§ˆβ‚‚β†
&p /+≑(/+≑KnotsΒ€Β°βŠ‚β†™Β―)βŠ™Β€+1β†˜2β‡‘βŠΈβ§» # Part 2 --> 21

"1,5,2,6,8,4,1,7,3,6"
βŠœβ‹•βŠΈβ‰ @,
βŠƒ(β§…<2+1⇑⧻◴|β§ˆβ‚‚β†)            # Possible cuts, existing strings.
/β†₯+βŠƒ(β‰‘ΛœβˆŠβŠ™Β€|≑(/+≑KnotsΒ€)βŠ™Β€) # Part3 --> 7
[–] ystael@beehaw.org 2 points 5 days ago

Common Lisp's loop macro has a pretty crazy list of features. New ones in this solution are for x on xs, which binds the iteration variable x to successive tails (instead of elements) of xs, and maximize, which is an alternative accumulator to sum. There's nothing interesting about the solution itself though -- simple brute-force enumeration.

(ql:quickload :str)

(defun parse-line (line)
  (mapcar #'parse-integer (str:split "," line)))

(defun read-inputs (filename)
  (let ((input-lines (uiop:read-file-lines filename)))
    (parse-line (car input-lines))))

(defun pairs (ns)
  (loop for tail on ns
        if (not (null (cdr tail)))
          collect (cons (car tail) (cadr tail))))

(defun through-center? (nails segment)
  (destructuring-bind (x . y) segment
    (= (mod (- x y) nails) (/ nails 2))))

(defun main-1 (filename)
  (let ((positions (read-inputs filename)))
    (loop for segment in (pairs positions)
          sum (if (through-center? 32 segment) 1 0))))

(defun crosses? (seg1 seg2)
  "When everything is normalized to 1..nails indices, seg1 crosses seg2 iff one of seg2's
  endpoints lies strictly between the endpoints of seg1, and the other one of seg2's endpoints
  lies strictly below or above the endpoints of seg1."
  (destructuring-bind (x1 . y1) seg1
    (destructuring-bind (x2 . y2) seg2
      (let ((big1 (max x1 y1))
            (small1 (min x1 y1)))
        (or (and (< small1 x2 big1)
                 (or (< y2 small1) (> y2 big1)))
            (and (or (< x2 small1) (> x2 big1))
                 (< small1 y2 big1)))))))

(defun main-2 (filename)
  (let ((positions (read-inputs filename)))
    (loop for seg-list on (pairs positions)
          sum (loop for seg2 in (cdr seg-list)
                    sum (if (crosses? (car seg-list) seg2) 1 0)))))

(defun score (threads seg)
  (loop for thread in threads
        sum (if (crosses? thread seg) 1 0)))

(defun main-3 (filename)
  (let* ((positions (read-inputs filename))
         (threads (pairs positions))
         (nails 256))
    (loop for x1 from 1 to nails
          maximize (loop for y1 from (1+ x1) to nails
                         maximize (score threads (cons x1 y1))))))
[–] janAkali@lemmy.sdf.org 2 points 6 days ago

Nim

Part 2 - I just really didn't want to think that day. So when puzzle asked me to check if lines intersect - I wrote the intersection checking solution with 2D points.

Part 3 is geometry + bruteforce.

proc solve_part1*(input: string): Solution =
  let pins = input.split(',').mapIt(parseInt(it))
  for i in 0 ..< pins.high:
    let d = abs(pins[i] - pins[i+1])
    if d == 16: inc result.intVal

proc ccw(A,B,C: Vec2): bool = (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)
proc isIntersection(A,B,C,D: Vec2): bool = ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)

proc solve_part2*(input: string): Solution =
  const two_pi = PI * 2
  const pin_count = 256

  var pins: array[pin_count, Vec2]
  for i in 0 ..< pin_count:
    let angle = two_pi * (i / pin_count)
    let point: Vec2 = (cos(angle), sin(angle))
    pins[i] = point

  let inst = input.split(',').mapIt(parseInt(it))
  var lines: seq[(Vec2, Vec2)]

  for i in 0 ..< inst.high:
    let A = pins[inst[i]-1]
    let B = pins[inst[i+1]-1]

    for (C, D) in lines:
      if isIntersection(A,B,C,D):
        inc result.intVal
    lines.add shortenSegment(A, B, 0.0001)

proc solve_part3*(input: string): Solution =
  const two_pi = PI * 2
  const pin_count = 256

  var pins: array[pin_count, Vec2]
  for i in 0 ..< pin_count:
    let angle = two_pi * (i / pin_count)
    let point: Vec2 = (cos(angle), sin(angle))
    pins[i] = point

  let inst = input.split(',').mapIt(parseInt(it))
  var lines: seq[(Vec2, Vec2)]

  for i in 0 ..< inst.high:
    let A = pins[inst[i]-1]
    let B = pins[inst[i+1]-1]
    lines.add shortenSegment(A, B, 0.0001)

  var bestSum = 0
  for i in 0 ..< pin_count:
    for j in i+1 ..< pin_count:
      let A = pins[i]
      let B = pins[j]
      var sum = 0
      for (C, D) in lines:
        if isIntersection(A,B,C,D): inc sum
      if sum > bestSum: bestSum = sum
  result := bestSum

Full solution at Codeberg: solution.nim

[–] hades@programming.dev 2 points 1 week ago

Rust

pub fn solve_part_1(input: &str) -> String {
    let numbers: Vec<i32> = input.split(",").map(|x| x.parse().unwrap()).collect();
    let mut count = 0;
    for i in 1..numbers.len() {
        if numbers[i].abs_diff(numbers[i - 1]) == 16 {
            count += 1;
        }
    }
    count.to_string()
}

pub fn solve_part_2(input: &str) -> String {
    let numbers: Vec<i32> = input.split(",").map(|x| x.parse().unwrap()).collect();
    let mut lines: Vec<(i32, i32)> = vec![];
    for i in 1..numbers.len() {
        let (a, b) = (numbers[i - 1], numbers[i]);
        if a > b {
            lines.push((b, a));
        } else {
            lines.push((a, b));
        }
    }
    let mut knots = 0;
    for i in 0..lines.len() {
        for j in 0..i {
            let (a, b) = lines[i];
            let (c, d) = lines[j];
            if a == c || a == d || b == c || b == d {
                continue;
            }
            let c_inside = c > a && c < b;
            let d_inside = d > a && d < b;
            if c_inside != d_inside {
                knots += 1;
            }
        }
    }
    knots.to_string()
}

pub fn solve_part_3(input: &str) -> String {
    let numbers: Vec<i32> = input.split(",").map(|x| x.parse().unwrap()).collect();
    let mut lines: Vec<(i32, i32)> = vec![];
    for i in 1..numbers.len() {
        let (a, b) = (numbers[i - 1], numbers[i]);
        if a > b {
            lines.push((b, a));
        } else {
            lines.push((a, b));
        }
    }
    let mut best_cut_threads = i64::MIN;
    for d in 1..=256 {
        for c in 1..d {
            let mut cut_threads = 0;
            for (a, b) in lines.iter().copied() {
                if a == c || a == d || b == c || b == d {
                    if a == c && b == d {
                        cut_threads += 1;
                    }
                    continue;
                }
                let c_inside = c > a && c < b;
                let d_inside = d > a && d < b;
                if c_inside != d_inside {
                    cut_threads += 1;
                }
            }
            if cut_threads > best_cut_threads {
                best_cut_threads = cut_threads;
            }
        }
    }
    best_cut_threads.to_string()
}
[–] lwhjp@piefed.blahaj.zone 2 points 1 week ago

Haskell

Woo! I got on the leaderboard at last. I don't think I've seen a problem like this one before, but fortunately it wasn't as tricky as it seemed at first glance.

import Control.Monad  
import Data.List  
import Data.List.Split  
import Data.Tuple  

readInput :: String -> [(Int, Int)]  
readInput = map fixOrder . (zip <*> tail) . map read . splitOn ","  
  where  
    fixOrder (x, y)  
      | x > y = (y, x)  
      | otherwise = (x, y)  

crosses (a, b) (c, d) =  
  not (a == c || a == d || b == c || b == d)  
    && ((a < c && c < b) /= (a < d && d < b))  

part1 n = length . filter ((== n `quot` 2) . uncurry (-) . swap)  

part2 n = sum . (zipWith countKnots <*> inits)  
  where  
    countKnots x strings = length $ filter (crosses x) strings  

part3 n strings =  
  maximum [countCuts (a, b) | a <- [1 .. n - 1], b <- [a + 1 .. n]]  
  where  
    countCuts x = length $ filter (\s -> x == s || x `crosses` s) strings  

main =  
  forM_  
    [ ("everybody_codes_e2025_q08_p1.txt", part1 32),  
      ("everybody_codes_e2025_q08_p2.txt", part2 256),  
      ("everybody_codes_e2025_q08_p3.txt", part3 256)  
    ]  
    $ \(input, solve) -> readFile input >>= print . solve . readInput