🎄 - 2023 DAY 15 SOLUTIONS -🎄

Day 15: Lens Library

Megathread guidelines

  • 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)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒 Thread is locked until there’s at least 100 2 star entries on the global leaderboard

Edit: 🔓 Unlocked

cacheson,
cacheson avatar

Nim

Almost caught up. Not much to say about this one. Part 1 was a freebie. Part 2 had a convoluted description, but was still pretty easy.

purplemonkeymad,

This felt … too simple. I think the hardest part of part two for me was reading comprehension. My errors were typically me not reading exactly was there.

Pythonimport re import math import argparse import itertools def int_hash(string:str) -> int: hash = 0 for c in [*string]: hash += ord© hash *= 17 hash = hash % 256 return hash class Instruction: def init(self,string:str) -> None: label,action,strength = re.split(‘([-=])’,string) self.label = label self.action = action if not strength: strength = 0 self.strength = int(strength) def repr(self) -> str: return f"Instruction(l={self.label}, a={self.action}, s={self.strength})" def str(self) -> str: stren = str(self.strength if self.strength > 0 else ‘’) return f"{self.label}{self.action}{stren}" class Lens: def init(self,label:str,focal_length:int) -> None: self.label:str = label self.focal_length:int = focal_length def repr(self) -> str: return f"Lens(label:{self.label},focal_length:{self.focal_length})" def str(self) -> str: return f"[{self.label} {self.focal_length}]" def main(line_list:str,part:int): init_sequence = line_list.splitlines(keepends=False)[0].split(‘,’) sum = 0 focal_array = dict<a href="">int,list[Lens]</a>for i in range(0,256): focal_array[i] = list<a href="">Lens</a>for s in init_sequence: hash_value = int_hash(s) sum += hash_value # part 2 stuff action = Instruction(s) position = int_hash(action.label) current_list = focal_array[position] existing_lens = list(filter(lambda x:x.label == action.label,current_list)) if len(existing_lens) > 1: raise Exception(“multiple of same lens in box, what do?”) match action.action: case ‘-’: if len(existing_lens) == 1: current_list.remove(existing_lens[0]) case ‘=’: if len(existing_lens) == 0: current_list.append(Lens(action.label,action.strength)) if len(existing_lens) == 1: existing_lens[0].focal_length = action.strength case _: raise Exception(“unknown action”) print(f"Part1: {sum}“) (focal_array) sum2 = 0 for i,focal_box in focal_array.items(): for l,lens in enumerate(focal_box): sum2 += ( (i+1) * (l+1) * lens.focal_length ) print(f"Part2: {sum2}”) if name == “main”: parser = argparse.ArgumentParser(description=“template for aoc solver”) parser.add_argument(“-input”,type=str) parser.add_argument(“-part”,type=int) args = parser.parse_args() filename = args.input if filename == None: parser.print_help() exit(1) part = args.part file = open(filename,‘r’) main(file.read(),part) file.close()

LeixB,

Haskell


<span style="color:#323232;">import Data.Array
</span><span style="color:#323232;">import qualified Data.ByteString.Char8 as BS
</span><span style="color:#323232;">import Data.Char (isAlpha, isDigit)
</span><span style="color:#323232;">import Relude
</span><span style="color:#323232;">import qualified Relude.Unsafe as Unsafe
</span><span style="color:#323232;">import Text.ParserCombinators.ReadP hiding (get)
</span><span style="color:#323232;">
</span><span style="color:#323232;">hash :: String -> Int
</span><span style="color:#323232;">hash = foldl' (a x -> (a + x) * 17 `mod` 256) 0 . fmap ord
</span><span style="color:#323232;">
</span><span style="color:#323232;">part1 :: ByteString -> Int
</span><span style="color:#323232;">part1 = sum . fmap (hash . BS.unpack) . BS.split ',' . BS.dropEnd 1
</span><span style="color:#323232;">
</span><span style="color:#323232;">-- Part 2
</span><span style="color:#323232;">
</span><span style="color:#323232;">type Problem = [Operation]
</span><span style="color:#323232;">
</span><span style="color:#323232;">type S = Array Int [(String, Int)]
</span><span style="color:#323232;">
</span><span style="color:#323232;">data Operation = Set String Int | Remove String deriving (Show)
</span><span style="color:#323232;">
</span><span style="color:#323232;">parse :: BS.ByteString -> Maybe Problem
</span><span style="color:#323232;">parse = fmap fst . viaNonEmpty last . readP_to_S parse' . BS.unpack
</span><span style="color:#323232;">  where
</span><span style="color:#323232;">    parse' = sepBy parseOperation (char ',') &lt;* char 'n' &lt;* eof
</span><span style="color:#323232;">    parseOperation =
</span><span style="color:#323232;">      munch1 isAlpha
</span><span style="color:#323232;">        >>= label -> (Remove label &lt;$ char '-') +++ (Set label . Unsafe.read &lt;$> (char '=' *> munch1 isDigit))
</span><span style="color:#323232;">
</span><span style="color:#323232;">liftOp :: Operation -> Endo S
</span><span style="color:#323232;">liftOp (Set label v) = Endo $ s ->
</span><span style="color:#323232;">  let (b, a) = second (drop 1) $ span ((/= label) . fst) (s ! hash label)
</span><span style="color:#323232;">   in s // [(hash label, b &lt;> [(label, v)] &lt;> a)]
</span><span style="color:#323232;">liftOp (Remove l) = Endo $ s -> s // [(hash l, filter ((/= l) . fst) (s ! hash l))]
</span><span style="color:#323232;">
</span><span style="color:#323232;">score :: S -> Int
</span><span style="color:#323232;">score m = sum $ join [(* (i + 1)) &lt;$> zipWith (*) [1 ..] (snd &lt;$> (m ! i)) | i &lt;- [0 .. 255]]
</span><span style="color:#323232;">
</span><span style="color:#323232;">part2 :: ByteString -> Maybe Int
</span><span style="color:#323232;">part2 input = do
</span><span style="color:#323232;">  ops &lt;- appEndo . foldMap liftOp . reverse &lt;$> parse input
</span><span style="color:#323232;">  pure . score . ops . listArray (0, 255) $ repeat []
</span>
lwhjp,
@lwhjp@lemmy.sdf.org avatar

Nice use of foldMap!

sjmulder,

C

Yes, it’s a hash table. Did I pick a language with built in hash tables? Of course I didn’t. Could I have used one of the many libraries implementing one? Sure. But the real question is, can we make do with stuffing things into a few static arrays at nearly zero memory and runtime cost? Yes!

In the spirit of Fred Brooks, it’ll suffice here to show my data structures:


<span style="font-weight:bold;color:#a71d5d;">struct </span><span style="color:#323232;">slot { </span><span style="font-weight:bold;color:#a71d5d;">char</span><span style="color:#323232;"> label[</span><span style="color:#0086b3;">8</span><span style="color:#323232;">]; </span><span style="font-weight:bold;color:#a71d5d;">int</span><span style="color:#323232;"> lens; };
</span><span style="font-weight:bold;color:#a71d5d;">struct </span><span style="color:#323232;">box { </span><span style="font-weight:bold;color:#a71d5d;">struct</span><span style="color:#323232;"> slot slots[</span><span style="color:#0086b3;">8</span><span style="color:#323232;">]; </span><span style="font-weight:bold;color:#a71d5d;">int</span><span style="color:#323232;"> nslots; };
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">static struct</span><span style="color:#323232;"> box boxes[</span><span style="color:#0086b3;">256</span><span style="color:#323232;">];
</span>

github.com/sjmulder/aoc/blob/master/…/day15.c

cvttsd2si,

Scala3


<span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">hash</span><span style="color:#323232;">(s: </span><span style="color:#0086b3;">String</span><span style="color:#323232;">): </span><span style="font-weight:bold;color:#a71d5d;">Long =</span><span style="color:#323232;"> s.foldLeft(</span><span style="color:#0086b3;">0</span><span style="color:#323232;">)((h, c) </span><span style="font-weight:bold;color:#a71d5d;">=> </span><span style="color:#323232;">(h + c)*</span><span style="color:#0086b3;">17</span><span style="color:#323232;"> % </span><span style="color:#0086b3;">256</span><span style="color:#323232;">)
</span><span style="color:#323232;">
</span><span style="color:#323232;">extension </span><span style="color:#0086b3;">A</span><span style="color:#323232;">
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">mapAtIndex</span><span style="color:#323232;">(idx: </span><span style="font-weight:bold;color:#a71d5d;">Long</span><span style="color:#323232;">, f: </span><span style="color:#0086b3;">A </span><span style="font-weight:bold;color:#a71d5d;">=> </span><span style="color:#0086b3;">A</span><span style="color:#323232;">): </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">A</span><span style="color:#323232;">] </span><span style="font-weight:bold;color:#a71d5d;">=
</span><span style="color:#323232;">        a.zipWithIndex.map((e, i) </span><span style="font-weight:bold;color:#a71d5d;">=> if</span><span style="color:#323232;"> i == idx then f(e) </span><span style="font-weight:bold;color:#a71d5d;">else</span><span style="color:#323232;"> e)
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">runProcedure</span><span style="color:#323232;">(steps: </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">String</span><span style="color:#323232;">]): </span><span style="font-weight:bold;color:#a71d5d;">Long =
</span><span style="color:#323232;">    @tailrec </span><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">go</span><span style="color:#323232;">(boxes: </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">List</span><span style="color:#323232;">[(</span><span style="color:#0086b3;">String</span><span style="color:#323232;">, </span><span style="font-weight:bold;color:#a71d5d;">Int</span><span style="color:#323232;">)]], steps: </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">String</span><span style="color:#323232;">]): </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">List</span><span style="color:#323232;">[(</span><span style="color:#0086b3;">String</span><span style="color:#323232;">, </span><span style="font-weight:bold;color:#a71d5d;">Int</span><span style="color:#323232;">)]] </span><span style="font-weight:bold;color:#a71d5d;">=
</span><span style="color:#323232;">        steps </span><span style="font-weight:bold;color:#a71d5d;">match
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">case </span><span style="color:#62a35c;">s</span><span style="color:#183691;">"</span><span style="color:#323232;">$label</span><span style="color:#183691;">-"</span><span style="color:#323232;"> :: t </span><span style="font-weight:bold;color:#a71d5d;">=>
</span><span style="color:#323232;">                go(boxes.mapAtIndex(hash(label), _.filter(_._1 != label)), t)
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">case </span><span style="color:#62a35c;">s</span><span style="color:#183691;">"</span><span style="color:#323232;">$label</span><span style="color:#183691;">=</span><span style="color:#323232;">$f</span><span style="color:#183691;">"</span><span style="color:#323232;"> :: t </span><span style="font-weight:bold;color:#a71d5d;">=>
</span><span style="color:#323232;">                go(boxes.mapAtIndex(hash(label), b </span><span style="font-weight:bold;color:#a71d5d;">=> 
</span><span style="color:#323232;">                    </span><span style="font-weight:bold;color:#a71d5d;">val </span><span style="color:#323232;">slot </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> b.map(_._1).indexOf(label)
</span><span style="color:#323232;">                    </span><span style="font-weight:bold;color:#a71d5d;">if</span><span style="color:#323232;"> slot != -</span><span style="color:#0086b3;">1</span><span style="color:#323232;"> then b.mapAtIndex(slot, (l, _) </span><span style="font-weight:bold;color:#a71d5d;">=> </span><span style="color:#323232;">(l, f.toInt)) </span><span style="font-weight:bold;color:#a71d5d;">else </span><span style="color:#323232;">(label, f.toInt) :: b
</span><span style="color:#323232;">                ), t)
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">case </span><span style="color:#323232;">_ </span><span style="font-weight:bold;color:#a71d5d;">=></span><span style="color:#323232;"> boxes
</span><span style="color:#323232;">    
</span><span style="color:#323232;">    go(</span><span style="color:#0086b3;">List</span><span style="color:#323232;">.fill(</span><span style="color:#0086b3;">256</span><span style="color:#323232;">)(</span><span style="color:#0086b3;">List</span><span style="color:#323232;">()), steps).zipWithIndex.map((b, i) </span><span style="font-weight:bold;color:#a71d5d;">=>
</span><span style="color:#323232;">        b.zipWithIndex.map((lens, ilens) </span><span style="font-weight:bold;color:#a71d5d;">=> </span><span style="color:#323232;">(</span><span style="color:#0086b3;">1</span><span style="color:#323232;"> + i) * (b.size - ilens) * lens._2).sum
</span><span style="color:#323232;">    ).sum
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">task1</span><span style="color:#323232;">(a: </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">String</span><span style="color:#323232;">]): </span><span style="font-weight:bold;color:#a71d5d;">Long =</span><span style="color:#323232;"> a.head.split(</span><span style="color:#183691;">","</span><span style="color:#323232;">).map(hash).sum
</span><span style="font-weight:bold;color:#a71d5d;">def </span><span style="font-weight:bold;color:#795da3;">task2</span><span style="color:#323232;">(a: </span><span style="color:#0086b3;">List</span><span style="color:#323232;">[</span><span style="color:#0086b3;">String</span><span style="color:#323232;">]): </span><span style="font-weight:bold;color:#a71d5d;">Long =</span><span style="color:#323232;"> runProcedure(a.head.split(</span><span style="color:#183691;">","</span><span style="color:#323232;">).toList)
</span>
capitalpb,

Had to take a couple days off, but this was a nice one to come back to. Will have to find some time today to go back and do one or two of the 3 that I missed. I don’t have much to say about this one - I had an idea almost immediately and it worked out without much struggle. There’s probably some cleaner ways to write parts of this, but I’m not too disappointed with how it turned out.

github.com/capitalpb/…/day15.rs


<span style="font-weight:bold;color:#a71d5d;">use crate</span><span style="color:#323232;">::Solver;
</span><span style="font-weight:bold;color:#a71d5d;">use </span><span style="color:#323232;">std::collections::HashMap;
</span><span style="color:#323232;">
</span><span style="color:#323232;">#[derive(Debug)]
</span><span style="font-weight:bold;color:#a71d5d;">struct </span><span style="color:#323232;">Lens {
</span><span style="color:#323232;">    label: String,
</span><span style="color:#323232;">    focal_length: </span><span style="font-weight:bold;color:#a71d5d;">u32</span><span style="color:#323232;">,
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">hash_algorithm</span><span style="color:#323232;">(input: </span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;</span><span style="font-weight:bold;color:#a71d5d;">str</span><span style="color:#323232;">) -> </span><span style="font-weight:bold;color:#a71d5d;">u32 </span><span style="color:#323232;">{
</span><span style="color:#323232;">    input
</span><span style="color:#323232;">        .</span><span style="color:#62a35c;">chars</span><span style="color:#323232;">()
</span><span style="color:#323232;">        .</span><span style="color:#62a35c;">fold</span><span style="color:#323232;">(</span><span style="color:#0086b3;">0</span><span style="color:#323232;">, |acc, ch| (acc </span><span style="font-weight:bold;color:#a71d5d;">+</span><span style="color:#323232;"> ch </span><span style="font-weight:bold;color:#a71d5d;">as u32</span><span style="color:#323232;">) </span><span style="font-weight:bold;color:#a71d5d;">* </span><span style="color:#0086b3;">17 </span><span style="font-weight:bold;color:#a71d5d;">% </span><span style="color:#0086b3;">256</span><span style="color:#323232;">)
</span><span style="color:#323232;">}
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">pub struct </span><span style="color:#323232;">Day15;
</span><span style="color:#323232;">
</span><span style="font-weight:bold;color:#a71d5d;">impl </span><span style="color:#323232;">Solver </span><span style="font-weight:bold;color:#a71d5d;">for </span><span style="color:#323232;">Day15 {
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">star_one</span><span style="color:#323232;">(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;self, input: </span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;</span><span style="font-weight:bold;color:#a71d5d;">str</span><span style="color:#323232;">) -> String {
</span><span style="color:#323232;">        input
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">trim_end</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">split</span><span style="color:#323232;">(</span><span style="color:#183691;">','</span><span style="color:#323232;">)
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(hash_algorithm)
</span><span style="color:#323232;">            .sum::()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">to_string</span><span style="color:#323232;">()
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">
</span><span style="color:#323232;">    </span><span style="font-weight:bold;color:#a71d5d;">fn </span><span style="font-weight:bold;color:#795da3;">star_two</span><span style="color:#323232;">(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;self, input: </span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;</span><span style="font-weight:bold;color:#a71d5d;">str</span><span style="color:#323232;">) -> String {
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">let mut</span><span style="color:#323232;"> boxes: HashMap</span><span style="font-weight:bold;color:#a71d5d;">> = </span><span style="color:#323232;">HashMap::new();
</span><span style="color:#323232;">
</span><span style="color:#323232;">        </span><span style="font-weight:bold;color:#a71d5d;">for</span><span style="color:#323232;"> instruction </span><span style="font-weight:bold;color:#a71d5d;">in</span><span style="color:#323232;"> input.</span><span style="color:#62a35c;">trim_end</span><span style="color:#323232;">().</span><span style="color:#62a35c;">split</span><span style="color:#323232;">(</span><span style="color:#183691;">','</span><span style="color:#323232;">) {
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">let </span><span style="color:#323232;">(label, focal_length) </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> instruction
</span><span style="color:#323232;">                .</span><span style="color:#62a35c;">split_once</span><span style="color:#323232;">(|ch| </span><span style="font-weight:bold;color:#a71d5d;">char</span><span style="color:#323232;">::is_ascii_punctuation(</span><span style="font-weight:bold;color:#a71d5d;">&</span><span style="color:#323232;">amp;ch))
</span><span style="color:#323232;">                .</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">();
</span><span style="color:#323232;">
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> box_number </span><span style="font-weight:bold;color:#a71d5d;">= </span><span style="color:#62a35c;">hash_algorithm</span><span style="color:#323232;">(label);
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> lenses </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> boxes.</span><span style="color:#62a35c;">entry</span><span style="color:#323232;">(box_number).</span><span style="color:#62a35c;">or_insert</span><span style="color:#323232;">(vec![]);
</span><span style="color:#323232;">
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">if</span><span style="color:#323232;"> focal_length </span><span style="font-weight:bold;color:#a71d5d;">== </span><span style="color:#183691;">"" </span><span style="color:#323232;">{
</span><span style="color:#323232;">                lenses.</span><span style="color:#62a35c;">retain</span><span style="color:#323232;">(|lens| lens.label </span><span style="font-weight:bold;color:#a71d5d;">!=</span><span style="color:#323232;"> label);
</span><span style="color:#323232;">                </span><span style="font-weight:bold;color:#a71d5d;">continue</span><span style="color:#323232;">;
</span><span style="color:#323232;">            }
</span><span style="color:#323232;">
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">let</span><span style="color:#323232;"> new_lens </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> Lens {
</span><span style="color:#323232;">                label: label.</span><span style="color:#62a35c;">to_string</span><span style="color:#323232;">(),
</span><span style="color:#323232;">                focal_length: focal_length.</span><span style="color:#62a35c;">parse</span><span style="color:#323232;">().</span><span style="color:#62a35c;">unwrap</span><span style="color:#323232;">(),
</span><span style="color:#323232;">            };
</span><span style="color:#323232;">
</span><span style="color:#323232;">            </span><span style="font-weight:bold;color:#a71d5d;">if let </span><span style="color:#0086b3;">Some</span><span style="color:#323232;">(lens_index) </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> lenses.</span><span style="color:#62a35c;">iter</span><span style="color:#323232;">().</span><span style="color:#62a35c;">position</span><span style="color:#323232;">(|lens| lens.label </span><span style="font-weight:bold;color:#a71d5d;">==</span><span style="color:#323232;"> new_lens.label) {
</span><span style="color:#323232;">                lenses[lens_index].focal_length </span><span style="font-weight:bold;color:#a71d5d;">=</span><span style="color:#323232;"> new_lens.focal_length;
</span><span style="color:#323232;">            } </span><span style="font-weight:bold;color:#a71d5d;">else </span><span style="color:#323232;">{
</span><span style="color:#323232;">                lenses.</span><span style="color:#62a35c;">push</span><span style="color:#323232;">(new_lens);
</span><span style="color:#323232;">            }
</span><span style="color:#323232;">        }
</span><span style="color:#323232;">
</span><span style="color:#323232;">        boxes
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">iter</span><span style="color:#323232;">()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|(box_number, lenses)| {
</span><span style="color:#323232;">                lenses
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">iter</span><span style="color:#323232;">()
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">enumerate</span><span style="color:#323232;">()
</span><span style="color:#323232;">                    .</span><span style="color:#62a35c;">map</span><span style="color:#323232;">(|(lens_index, lens)| {
</span><span style="color:#323232;">                        (box_number </span><span style="font-weight:bold;color:#a71d5d;">+ </span><span style="color:#0086b3;">1</span><span style="color:#323232;">) </span><span style="font-weight:bold;color:#a71d5d;">* </span><span style="color:#323232;">(lens_index </span><span style="font-weight:bold;color:#a71d5d;">as u32 + </span><span style="color:#0086b3;">1</span><span style="color:#323232;">) </span><span style="font-weight:bold;color:#a71d5d;">*</span><span style="color:#323232;"> lens.focal_length
</span><span style="color:#323232;">                    })
</span><span style="color:#323232;">                    .sum::()
</span><span style="color:#323232;">            })
</span><span style="color:#323232;">            .sum::()
</span><span style="color:#323232;">            .</span><span style="color:#62a35c;">to_string</span><span style="color:#323232;">()
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">}
</span>
Gobbel2000,
@Gobbel2000@feddit.de avatar

Rust

Part 1 was super simple with wrapping_add and wrapping_mul on a u8. Building an actual hash map in Part 2 was nice.

sjmulder,

That array initialisation is pure poetry! 😄

lwhjp,
@lwhjp@lemmy.sdf.org avatar

I’m not fluent in Rust, but is this something like the C++ placement new? Presumably just declaring a table of Vecs won’t automatically call the default constructor? (Sorry for my total ignorance – pointers to appropriate reading material appreciated)

Gobbel2000,
@Gobbel2000@feddit.de avatar

You can create an array filled with all the same values in Rust, but only if all values have the same memory representation because they will be copied. That just doesn’t work with Vec’s, because they must all have their own unique pointer. And to have uninitialized values at first (think NULL-pointers for every Vec) while creating each Vec, something like this is apparently needed.

The appropriate way would certainly have been to store the map as a Vec> instead of an array, but I just wanted to see if could.

lwhjp,
@lwhjp@lemmy.sdf.org avatar

Ah, I see! Thank you.

hades,

Python

0.248 line-seconds (sixth simplest so far after days 6, 2, 1, 4 and 9).

Also on Github


<span style="color:#323232;">import collections
</span><span style="color:#323232;">import re
</span><span style="color:#323232;">
</span><span style="color:#323232;">from .solver import Solver
</span><span style="color:#323232;">
</span><span style="color:#323232;">
</span><span style="color:#323232;">def _hash(string: str) -> int:
</span><span style="color:#323232;">  result = 0
</span><span style="color:#323232;">  for c in string:
</span><span style="color:#323232;">    result = (result + ord(c)) * 17 % 256
</span><span style="color:#323232;">  return result
</span><span style="color:#323232;">
</span><span style="color:#323232;">def _assert_full_match(pattern: str, string: str):
</span><span style="color:#323232;">  m = re.fullmatch(pattern, string)
</span><span style="color:#323232;">  if not m:
</span><span style="color:#323232;">    raise RuntimeError(f'pattern {pattern} does not match {string}')
</span><span style="color:#323232;">  return m
</span><span style="color:#323232;">
</span><span style="color:#323232;">class Day15(Solver):
</span><span style="color:#323232;">  input: list[str]
</span><span style="color:#323232;">
</span><span style="color:#323232;">  def __init__(self):
</span><span style="color:#323232;">    super().__init__(15)
</span><span style="color:#323232;">
</span><span style="color:#323232;">  def presolve(self, input: str):
</span><span style="color:#323232;">    self.input = input.rstrip().split(',')
</span><span style="color:#323232;">
</span><span style="color:#323232;">  def solve_first_star(self) -> int:
</span><span style="color:#323232;">    return sum(_hash(string) for string in self.input)
</span><span style="color:#323232;">
</span><span style="color:#323232;">  def solve_second_star(self) -> int:
</span><span style="color:#323232;">    boxes = [collections.OrderedDict() for _ in range(256)]
</span><span style="color:#323232;">    for instruction in self.input:
</span><span style="color:#323232;">      label, op, value = _assert_full_match(r'([a-z]+)([=-])(d*)', instruction).groups()
</span><span style="color:#323232;">      box = boxes[_hash(label)]
</span><span style="color:#323232;">      match op:
</span><span style="color:#323232;">        case '-':
</span><span style="color:#323232;">          if label in box:
</span><span style="color:#323232;">            del box[label]
</span><span style="color:#323232;">        case '=':
</span><span style="color:#323232;">          box[label] = value
</span><span style="color:#323232;">    return sum((1 + box_idx) * (1 + lens_idx) * int(value)
</span><span style="color:#323232;">                for box_idx, box in enumerate(boxes)
</span><span style="color:#323232;">                for lens_idx, (_, value) in enumerate(box.items()))
</span>
mykl, (edited )
@mykl@lemmy.world avatar

Dart

Just written as specced. If there’s any underlying trick, I missed it totally.

9ms * 35 LOC ~= 0.35, so it’ll do.


<span style="color:#323232;">int decode(String s) => s.codeUnits.fold(0, (s, t) => ((s + t) * 17) % 256);
</span><span style="color:#323232;">
</span><span style="color:#323232;">part1(List lines) => lines.first.split(',').map(decode).sum;
</span><span style="color:#323232;">
</span><span style="color:#323232;">part2(List lines) {
</span><span style="color:#323232;">  var rules = lines.first.split(',').map((e) {
</span><span style="color:#323232;">    if (e.contains('-')) return ('-', e.skipLast(1), 0);
</span><span style="color:#323232;">    var parts = e.split('=');
</span><span style="color:#323232;">    return ('=', parts.first, int.parse(parts.last));
</span><span style="color:#323232;">  });
</span><span style="color:#323232;">  var boxes = Map.fromEntries(List.generate(256, (ix) => MapEntry(ix, [])));
</span><span style="color:#323232;">  for (var r in rules) {
</span><span style="color:#323232;">    if (r.$1 == '-') {
</span><span style="color:#323232;">      boxes[decode(r.$2)]!.removeWhere((l) => l.$1 == r.$2);
</span><span style="color:#323232;">    } else {
</span><span style="color:#323232;">      var box = boxes[decode(r.$2)]!;
</span><span style="color:#323232;">      var lens = box.indexed().firstWhereOrNull((e) => e.value.$1 == r.$2);
</span><span style="color:#323232;">      var newlens = (r.$2, r.$3);
</span><span style="color:#323232;">      (lens == null) ? box.add(newlens) : box[lens.index] = newlens;
</span><span style="color:#323232;">    }
</span><span style="color:#323232;">  }
</span><span style="color:#323232;">  return boxes.entries
</span><span style="color:#323232;">      .map((b) =>
</span><span style="color:#323232;">          (b.key + 1) *
</span><span style="color:#323232;">          b.value.indexed().map((e) => (e.index + 1) * e.value.$2).sum)
</span><span style="color:#323232;">      .sum;
</span><span style="color:#323232;">}
</span>
hades,

9ms * 35 LOC is ~0.350 tho

mykl,
@mykl@lemmy.world avatar

That’s why I normally let computers do my sums for me. Corrected now.

janAkali, (edited )

Nim

My whole solution can be expressed in just two words: Ordered HashTable

Total runtime: 0.068 line-seconds (40 LOC * 1.7 ms)
Puzzle rating: exceptionally confusing description 4/10
Code: cleaned up solution with types
Snippet:


<span style="color:#323232;">proc getHash(s: string): int =
</span><span style="color:#323232;">  for c in s:
</span><span style="color:#323232;">    result = ((result + c.ord) * 17) mod 256
</span><span style="color:#323232;">
</span><span style="color:#323232;">proc solve(lines: seq[string]): AOCSolution[int] =
</span><span style="color:#323232;">  var boxes: array[256, OrderedTable[string, int]]
</span><span style="color:#323232;">  for line in lines:
</span><span style="color:#323232;">    block p1:
</span><span style="color:#323232;">      result.part1 += line.getHash()
</span><span style="color:#323232;">
</span><span style="color:#323232;">    block p2:
</span><span style="color:#323232;">      if line.endsWith('-'):
</span><span style="color:#323232;">        var name = line.strip(leading=false, chars={'-'})
</span><span style="color:#323232;">        boxes[getHash(name)].del(name)
</span><span style="color:#323232;">      else:
</span><span style="color:#323232;">        let (name, _, value) = line.partition("=")
</span><span style="color:#323232;">        boxes[getHash(name)][name] = value[0].ord - '0'.ord
</span><span style="color:#323232;">
</span><span style="color:#323232;">  for bi, box in boxes:
</span><span style="color:#323232;">    if box.len < 1: continue
</span><span style="color:#323232;">    for vi, val in enumerate(box.values):
</span><span style="color:#323232;">      result.part2 += (bi+1) * (vi+1) * val
</span>
lwhjp,
@lwhjp@lemmy.sdf.org avatar

Haskell

Took a while to figure out what part 2 was all about. Didn’t have the energy to golf this one further today, so looking forward to seeing the other solutions!

Solution0.3 line-secondsimport Data.Char import Data.List import Data.List.Split import qualified Data.Vector as V hash :: String -> Int hash = foldl’ (a c -> ((a + ord c) * 17) rem 256) 0 hashmap :: [String] -> Int hashmap = focus . V.toList . foldl’ step (V.replicate 256 []) where focus = sum . zipWith focusBox [1 …] focusBox i = sum . zipWith (j (_, z) -> i * j * z) [1 …] . reverse step boxes s = let (label, op) = span isLetter s i = hash label in case op of [‘-’] -> V.accum (flip filter) boxes [(i, (/= label) . fst)] (‘=’ : z) -> V.accum replace boxes [(i, (label, read z))] replace ls (n, z) = case findIndex ((== n) . fst) ls of Just j -> let (a, _ : b) = splitAt j ls in a ++ (n, z) : b Nothing -> (n, z) : ls main = do input <- splitOn “,” . head . lines <$> readFile “input15” print $ sum . map hash $ input print $ hashmap input

  • All
  • Subscribed
  • Moderated
  • Favorites
  • advent_of_code@programming.dev
  • ngwrru68w68
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • InstantRegret
  • GTA5RPClips
  • Youngstown
  • everett
  • slotface
  • rosin
  • osvaldo12
  • mdbf
  • kavyap
  • cubers
  • megavids
  • modclub
  • normalnudes
  • tester
  • khanakhh
  • Durango
  • ethstaker
  • tacticalgear
  • Leos
  • provamag3
  • anitta
  • cisconetworking
  • JUstTest
  • lostlight
  • All magazines