this post was submitted on 13 Nov 2025
1 points (54.5% 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 6: Mentorship Matrix

  • 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 1 points 2 days ago

Scheme/Guile

Part 3 was a fun little challenge.

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

(define (parse-file file-name) (string-trim-both (call-with-input-file file-name get-string-all)))

(let* ((line (parse-file "notes/everybody_codes_e2025_q06_p1.txt"))
       (line-length (string-length line)))
  (let loop ((i 0) (knight-count 0) (mentor-count 0))
    (if {i < line-length}
        (let ((letter (string-ref line i)))
          (loop (1+ i) (+ knight-count (if (eq? letter #\A) 1 0)) (+ mentor-count (if (eq? letter #\a) knight-count 0))))
        (format #t "P1 Answer: ~a\n\n" mentor-count))))

(let* ((line (parse-file "notes/everybody_codes_e2025_q06_p2.txt"))
       (line-length (string-length line)))
  (let loop ((i 0) (knight-counts '()) (mentor-count 0))
    (if {i < line-length}
        (let ((letter (string-ref line i)))
          (loop
            (1+ i)
            (if (char-upper-case? letter) (assq-set! knight-counts letter (1+ (or (assq-ref knight-counts letter) 0))) knight-counts)
            (+ mentor-count (if (char-lower-case? letter) (or (assq-ref knight-counts (char-upcase letter)) 0) 0))))
        (format #t "P2 Answer: ~a\n\n" mentor-count))))


(let* ((line (parse-file "notes/everybody_codes_e2025_q06_p3.txt"))
       (line-length (string-length line)))
  (let loop ((i 0) (mentor-count 0))
    (if {i < line-length}
        (let ((letter (string-ref line i)))
          (loop
            (1+ i)
            (+ mentor-count
               (if (char-lower-case? letter)
                   (let loop ((j (- i 1000)) (mentors-here 0))
                     (if {j <= (+ i 1000)}
                         (loop
                           (1+ j)
                           (+ mentors-here
                              (if {(string-ref line {j modulo line-length}) eq? (char-upcase letter)}
                                  (if (and {0 <= j} {j < line-length}) 1000 999)
                                  0)))
                         mentors-here))
                   0))))
        (format #t "P3 Answer: ~a\n\n" mentor-count))))
[–] mykl@lemmy.world 2 points 6 days ago

Uiua

Straightforward until part3. I left the naive approach running while I put together the version below, but of course the better algorithm got there first.

Prep ← (
  β‰ΛœβŠŸΒ°βŠβ‰‘β–‘                # store char with index
  βŠ•(βŠŸβŠƒ(⊒⊒|░≑(Β°β–‘βŠ£)))βŠ›βŠΈβ‰‘β—‡βŠ’ # group them
  β‰β†―βˆž_6βŠββŠΈβ‰‘(Β°β–‘βŠ’βŠ’)        # re-arrange
  β–½=1β—Ώ2°⊏                # drop labels, as we never used them...
)
/+/+⊞>βˆ©Β°β–‘Β°βŠŸβŠ’Prep "ABabACacBCbca"     # Part1
/+≑(/+/+⊞>βˆ©Β°β–‘Β°βŠŸ)Prep "ABabACacBCbca" # Part2

# Note that the pattern repeats, so the only distinct values
# are in the first run and last run. Everything in between
# will be identical. Only works when distance < string length...
⟜Prep "AABCBABCABCabcabcABCCBAACBCa"
Rep   ← 2
Split ← [1 -2Rep 1] # multipliers for the three results for each profession.
Dist  ← 10
≑(≑(βŠŸβˆ©β–‘)βŠƒ(≑+βŠ™(Β€Β°β–‘βŠ’)|€♭≑+βŠ™(Β€Β°β–‘βŠ£)))€×⇑3β§» # Create the start, middle, end set for each.
/+≑(/+Γ—Split≑(/+/+⊞(≀Dist⌡-)βˆ©Β°β–‘Β°βŠŸ))
[–] ystael@beehaw.org 2 points 6 days ago

In part 3 we can avoid thinking about the structure of the input string (left vs center vs right portions) and get the efficiency back by building up the counts of available mentors in each window position incrementally. The result is more code and takes a lot of space, but minimizes the number of irregular boundary cases.

(ql:quickload :str)

(defun parse-line (line)
  (let ((result (make-hash-table :test #'equal)))
    (loop for n from 0 to (1- (length line))
          for c = (char line n)
          for old = (gethash c result)
          do (setf (gethash c result) (cons n old)))
    result))

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

(defun pairs (pos-hash early-type late-type)
  (loop for early-index in (gethash early-type pos-hash)
        sum (length (remove-if #'(lambda (late-index) (< late-index early-index))
                               (gethash late-type pos-hash)))))

(defun main-1 (filename)
  (pairs (read-inputs filename) #\A #\a))

(defun main-2 (filename)
  (let ((pos-hash (read-inputs filename)))
    (reduce #'+
            (mapcar #'(lambda (type-pair) (apply #'pairs (cons pos-hash type-pair)))
                    '((#\A #\a) (#\B #\b) (#\C #\c))))))

(defun char-at (base-string pos)
  (char base-string (mod pos (length base-string))))

(defun type-window-counts (base-string copies radius type)
  (let* ((max-pos (* copies (length base-string)))
         (counts (make-array max-pos)))
    (setf (aref counts 0)
          (loop for i from 0 to radius
                sum (if (eql type (char-at base-string i)) 1 0)))
    (loop for i from 1 to (1- max-pos)
          do (let ((new-count
                     (+ (aref counts (1- i))
                        (if (and (< (+ i radius) max-pos)
                                 (eql type (char-at base-string (+ i radius))))
                            1 0)
                        (if (and (>= (- i (1+ radius)) 0)
                                 (eql type (char-at base-string (- i (1+ radius)))))
                            -1 0))))
               (setf (aref counts i) new-count)))
    counts))

(defun window-counts (base-string copies radius types)
  (mapcar #'(lambda (type)
              (cons type (type-window-counts base-string copies radius type)))
          types))

(defun count-pairs (base-string copies source-type target-type-window-counts)
  (let ((max-pos (* copies (length base-string))))
    (loop for i from 0 to (1- max-pos)
          sum (if (eql source-type (char-at base-string i))
                  (aref target-type-window-counts i) 0))))

(defun main-3 (filename)
  (let* ((base-string (car (uiop:read-file-lines filename)))
         (copies 1000)
         (radius 1000)
         (type-pairs '((#\a #\A) (#\b #\B) (#\c #\C)))
         (window-counts (window-counts base-string copies radius (mapcar #'cadr type-pairs))))
    (reduce #'+
            (mapcar #'(lambda (type-pair)
                        (count-pairs base-string copies (car type-pair)
                                     (cdr (assoc (cadr type-pair) window-counts))))
                    type-pairs))))
[–] janAkali@lemmy.sdf.org 2 points 6 days ago* (last edited 6 days ago)

Nim

parts 1 and 2 - easy

For part 3 - When I first looked at the example input - it seemed a bit daunting to solve. But then I had a hunch and decided to check the real input and turns out - I was right! The real input is easier to solve because it's longer than 1000 chars.

This means that there is only 3 possible configurations we care about in repeated input: leftmost section, rightmost section and 998 identical sections in the middle. We solve each individually and sum them.

Another trick I used is looking up mentors with modulo to avoid copying the input.

proc solve_part1*(input: string): Solution =
  var mentors: CountTable[char]
  for c in input:
    if c notin {'a','A'}: continue
    if c.isUpperAscii: mentors.inc c
    else:
      result.intVal += mentors.getOrDefault(c.toUpperAscii)

proc solve_part2*(input: string): Solution =
  var mentors: CountTable[char]
  for c in input:
    if c.isUpperAscii: mentors.inc c
    else:
      result.intVal += mentors.getOrDefault(c.toUpperAscii)

proc solve_part3*(input: string): Solution =
  var mentors: Table[char, seq[int]]
  for index in -1000 ..< input.len + 1000:
    let mi = index.euclMod input.len
    if input[mi].isLowerAscii: continue
    let lower = input[mi].toLowerAscii
    if mentors.hasKeyOrPut(lower, @[index]):
      mentors[lower].add index

  var most, first, last = 0
  for ci, ch in input:
    if ch.isUpperAscii: continue
    for mi in mentors[ch]:
      let dist = abs(mi - ci)
      if dist <= 1000:
        inc most
        if mi >= 0: inc first
        if mi <= input.high: inc last

  result := first + (most * 998) + last

Full solution at Codeberg: solution.nim

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

Rust

use std::collections::HashMap;
use itertools::Itertools;

pub fn solve_part_1(input: &str) -> String {
    let mut mentors = 0;
    let mut pairs = 0;
    for ch in input.chars() {
        match ch {
            'A' => mentors += 1,
            'a' => pairs += mentors,
            _ => {}
        }
    }
    pairs.to_string()
}

pub fn solve_part_2(input: &str) -> String {
    let mut mentors: HashMap<char, i64> = HashMap::new();
    let mut pairs = 0;
    for ch in input.chars() {
        match ch {
            'A'..='Z' => *mentors.entry(ch).or_default() += 1,
            'a'..='z' => pairs += *mentors.entry(ch.to_ascii_uppercase()).or_default(),
            _ => panic!("unexpected character {ch}"),
        }
    }
    pairs.to_string()
}

pub fn solve_part_3(input: &str) -> String {
    let data: Vec<_> = input.chars().collect();
    let len = data.len();
    let mentors: HashMap<char, Vec<usize>> = data
        .iter()
        .enumerate()
        .map(|(i, ch)| (*ch, i))
        .into_group_map();
    let mut pairs: i64 = 0;
    for (squire_position, ch) in data.into_iter().enumerate() {
        if ch.is_ascii_lowercase() {
            for mentor_position in mentors.get(&ch.to_ascii_uppercase()).unwrap() {
                if squire_position.abs_diff(*mentor_position) <= 1000 {
                    pairs += 1000;
                } else if (squire_position as isize)
                    .wrapping_sub_unsigned(len)
                    .abs_diff(*mentor_position as isize)
                    <= 1000
                    || (*mentor_position as isize)
                        .wrapping_sub_unsigned(len)
                        .abs_diff(squire_position as isize)
                        <= 1000
                {
                    pairs += 999;
                }
            }
        }
    }
    pairs.to_string()
}
[–] lwhjp@piefed.blahaj.zone 2 points 1 week ago

Haskell

It took me an embarrassingly long time to figure out what was going on with this one.

You could go a bit faster by splitting the list into beginning/middle/end parts, but I like the simplicity of this approach.

import Control.Monad (forM_)  
import Data.Char (toUpper)  
import Data.IntMap.Strict qualified as IntMap  
import Data.List (elemIndices)  
import Data.Map qualified as Map  

{-  
  f is a function which, given a lookup function and an index  
  returns the number of mentors for the novice at that position.  
  The lookup function returns the number of knights up to but  
  not including a specified position.  
-}  
countMentorsWith f input = Map.fromList [(c, go c) | c <- "abc"]  
  where  
    go c =  
      let knights = elemIndices (toUpper c) input  
          counts = IntMap.fromDistinctAscList $ zip knights [1 ..]  
          preceding = maybe 0 snd . (`IntMap.lookupLT` counts)  
       in sum $ map (f preceding) $ elemIndices c input  

part1 = (Map.! 'a') . countMentorsWith id  

part2 = sum . countMentorsWith id  

part3 d r = sum . countMentorsWith nearby . concat . replicate r  
  where  
    nearby lookup i = lookup (i + d + 1) - lookup (i - d)  

main =  
  forM_  
    [ ("everybody_codes_e2025_q06_p1.txt", part1),  
      ("everybody_codes_e2025_q06_p2.txt", part2),  
      ("everybody_codes_e2025_q06_p3.txt", part3 1000 1000)  
    ]  
    $ \(input, solve) -> readFile input >>= print . solve