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/

  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    2 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
    link
    fedilink
    arrow-up
    2
    ·
    2 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
    link
    fedilink
    arrow-up
    2
    ·
    3 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

  • Amy@piefed.blahaj.zone
    link
    fedilink
    English
    arrow-up
    2
    ·
    4 days 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  
    
  • hades@programming.devOPM
    link
    fedilink
    arrow-up
    3
    ·
    4 days 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()
    }