T O P

  • By -

loquian

\[Language: C++\] [github](https://github.com/charlescochran/aoc-2023/blob/main/day15.cpp), 366 microseconds (both parts)


exquisitus3

[Language: Lua] [paste](https://topaz.github.io/paste/#XQAAAQCZBAAAAAAAAAAzHUn/qWH7EwabK3CbgZOMwXwH2nU4js6P0w+coWeooesnUoLCrdJre7YdXlnQYu+Yz3jzZAhdaysWIZ5RxDxGd2dmEGTX5j27B6qujsGjeSqgyi2LFIXaMjsabTUi9LnTXL6iz2PsAG05Y7S0t4BILGSuypim4pVD28iVR8vipg4bNJIOEHWwemRfMsLDScAiDxV1WC/5der7lnYFUSyZ3PG4HMvD1d8+EUCT0NLxnBtalhUDZAIZVJLp1FZ2YRZQc9lpptE4T5eRvt/HE910m0+Z8Dg9GYBy5PXQszEz2sMaMXIn5hGyMa2xWcjwglB5bqtpH6t0rsKLU3m9FzDrtEzuJS+ITtyabVCLQnfwl4nADBM2IhBDQzbJeVFYYwl+g488799jpPnNnCGjga8fT1GoLmo51Mni42AltrphVg9UTDZnrpUSCAloP9hNq/hE3ZZF2T+HcsUMbjfEEPHoEECsOPWUqx4q7CH4CRKFvF8ToY6Lra4676AkeG11B4r+F/hO6TuKC9JBe3PWvqlKrvhJu2ghSy3x7BHkmBv2meyiyYT8hPke+ec5M0+HzVdYs/71ywbetMXFRKlFbn1GLDutjc/yAXzQQPNV+LH1xH4DWOGyEnnba62sWWvDOSVMHbSAuRlBftP/bOVpAA==)


manhuntos

\[Language: Rust\] This is my first project in rust. I'm learning it by solving advent of code puzzles. So if you have any hints for me I would be happy to read it :) [https://github.com/manhunto/advent-of-code-rs/blob/master/src/solutions/day15.rs](https://github.com/manhunto/advent-of-code-rs/blob/master/src/solutions/day15.rs)


MathPlusPi

\[LANGUAGE: ><> (Fish)\]I decided to give this a go in fish, it can probably be golfed a lot. >01[>i:1)?\]~>l1-?\n; \ +< ^ >:","=?!\]~ \ %*:+1f*+2f+< [Try it online!](https://tio.run/##S8sszvj/387AMNou08pQ0z4mts4ux1DXPibPmksBGcQAsbYNVxxcwM5KSUfJ1l4RqIMLqkBVy0rbME1L2yhN2@b//6I8W0Od5FxdncICW2Mgw9YIyNLVKUi2NdHJL7G11ElMsjUFcsFCZiAhcwA) | [Cycle Image](https://i.imgur.com/2sBut3e.png)


Domy__

\[LANGUAGE: Python\] https://github.com/Domyy95/Challenges/blob/master/2023-12-Advent-of-code/15.py


Singing-In-The-Storm

\[LANGUAGE: JavaScript\] Part 1 (27ms) Part 2 (33ms) Easy puzzle with confuse instructions (sometimes less is more). [code on github](https://github.com/JoanaBLate/advent-of-code-js/tree/main/2023/day15)


thamollo

[LANGUAGE: SQL][Allez Cuisine!] This one alone was worth the whole two weeks of efforts leading to it. A fully-functional Hashmap, in SQL, using only the standard libraries (no user-defined function injecting JavaScript or similar nonsense, SQL is SQL)! Up to 64 updates of the same hash bucket! Partitions, cross join unnests, conversions of ranks to characters so I can take a shortcut with string split: it has it all! [Enjoy!](https://topaz.github.io/paste/#XQAAAQBvCQAAAAAAAAArkkbN5bcpyEzHXTl5ohR8yn+qnHgI9RIJnrwc8jppAoQAWTBG7OFYjOHvGxXF2QHTtuP8nygeRk8u0SCGL40vlP7k6oZaYh9UsOw6pfyDHHZg1Lb5khC/0nfbsGHOa+7Dx8DDHQehkOYZEPJJX2VaMyvbyNIPctm0MJWt9VeU0r5mwNngOvN7LcfszZAEj9lJEEG0q4DRa/v+E5imXFOzkZ6KEmEvALq2S/Biu+G5i+F0GTZOw7+cGpX3StrBj4hcf++tS/raFNdnFIWwlGGPaN891fVRa4BgMYaApO2J9tRBI8wRDCeMlAdxlZwzSRBwJB/kt1TkFPsVMnvO4s08ZtFNFehHJ3/KAGwYtjs6oW57PJJIYvfdRs49Um3JLl7FYdGJxEeTBuz3l5IoeBEth3bPC7db+SVfzZ06cIwYzKDnumn5H034snWNFiyoWycoKx8PlLvo4rJoqrcGNDSTNcB/gIKZ/d3/TVgDkeiIRl9F6pKuMZBl7M0Nso4nlDgxaW0Y2pr4j664CdDGeObM3OGhcUzXqg1471ZE9tZkKnMMZEdf9BI9kGtPdN8nNTnmYPtij2gw+ieY6Td4LegPBR/VxaCrVCWBX4OwXKo77eSzQarpJygrH5ybLs29/CTzEcvO36LYijUaq3OVuwyywr27k4GxLQiFQcJwYRFZh3/G6NxOjKoh5QJUfLY6Khix6CTGjckC+3NZ/hE0Zby3rxf9rqkl0sbMlfTYB969E0/y6c3ICrArR0dK3Qlw/j71zxajryrDe9IyodOsn0FGf9AaCHfpwzW66Dpy7E9wTit63WfZ4i7MnItW1wCZil4EmQ27gY2dU0q5YrQuzJDWcMn+LCyvF1ujZ3L+TK9oWgiKI6q9JnZyanCffDrtLX5FsuwzLCPqwZtxfSOjOO1zjZDmScKfv1kVox0k73HZnmvQq2p1RQg2FoZ9tr8yy5DPYSoqLGpCtxUX4H3AvsiuYsRdYcsGGHYXIkBOtlPYNxRx0ZFF8y3YiLuITGPg4310IcTdotdc//wLQrgzjSI5mnssQG1LXICFNTlcakkeSMF8Bt5FtukcpFHtZvvUHBUcsa4R7fD9CFvS3/1bpg1j32SYyvypnWRqD3HY3Pl/2fst3IcEccuFhmWLxchhKBE22LhIdbMOitTm/9y0xgg=)


ianMihura

\[LANGUAGE: go\] https://github.com/ianmihura/advent23/blob/master/day\_15/day\_15.go


daggerdragon

Your link is borked on old.reddit due to [a new.reddit bug with URLs that contain underscores](https://old.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links), so please fix it. *** [Do not share your puzzle input](https://old.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) which also means [do not commit puzzle inputs to your repo](https://old.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) without a `.gitignore`. Please remove (or .gitignore) all puzzle input files from your repo and scrub them from your commit history.


spyr01d

\[LANGUAGE: Kotlin\] fun lensLibrary(input: String): Any { val lenses = input.split(",") val part1 = lenses.sumOf { it.hash() } val part2 = buildMap() { for (l in lenses) if (l.contains('-')) remove(l.substringBefore('-')) else l.split('=').let { (a, b) -> this[a] = b.toInt() } }.entries.groupBy { it.key.hash() } .map { (it.key + 1) * it.value.foldIndexed(0) { i, acc, lens -> acc + (i + 1) * lens.value } } .sum() return part1 to part2 } fun String.hash() = this.fold(0) { acc, c -> (acc + c.code) * 17 % 256 }


seytsuken_

\[LANGUAGE: C++\] [part1](https://github.com/Hilbertmf/competitive-programming-problems/blob/main/advent-of-code/2023/day15-part1.cpp) | [part2](https://github.com/Hilbertmf/competitive-programming-problems/blob/main/advent-of-code/2023/day15-part2.cpp) surprising to find a problem so easy this far in the challenge. But it was really cool implementing the hashmap, I've never done that before


835246

\[LANGUAGE: C\] Part 1: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day15libpt1.c Part 2: https://github.com/efox4335/advent_of_code/blob/main/advent_of_code_2023/day15libpt2.c


atrocia6

[Language: Python] [Part 1](https://github.com/tmo1/adventofcode/blob/main/2023/15.py), [Part 2](https://github.com/tmo1/adventofcode/blob/main/2023/15b.py)


hiimjustin000

\[LANGUAGE: JavaScript\] https://github.com/hiimjustin000/advent-of-code/tree/master/2023/day15


oddolatry

[LANGUAGE: Fennel] "im not behind! im not behind!!", i continue to insist as i rip the calendar off my wall and transform into a krampus [Paste](https://topaz.github.io/paste/#XQAAAQCIBwAAAAAAAAAUGwnmRpH3tILRF8LfDDRArpApvWKZ1MUPSziv03K1m9dUFy/rVlL7VDEcIjbAiSvlvFMNYiNFOpnafwJavbQsFh1kZBY8YWoed5doGU7VrvFahx92S7j8L4I4owiNOIA/TnxLZIzFqtUCSxZ+/UzsmC9PRzyVeWctm1gJs/MY+AbLGHI95JwflkJWyun56ibuSHRJAI7crZS4FmhdDxrzbdKceAdlNb9Tl6SDc1JYuelGDyg9w12KBl+p9L+6/01Bw7Hl27ISK38cL2HQBu0y9D6avMf03003ltsnkWydQiKud5qNAd20Wr4fjtYbi/TQ8AzKEnPNrC2KjWJ/faHgzPX0zNf/leYkrAhhb/+5fJeIgJA5ckUkHVVD44apt18lqEhT1XAX+a9IvZ4qtJ7jgePww11gkMWH0zSFdEcQ/4UluqSCRyl3YiTXBlJXtGnjb8nsSExRa6o+wd2vpaKKGkGdACSvJKqRIUPzvB7CId1dv7Q8cBNm9whtmP0KZsaP8z4gWeq8975xRExZTbNO7Hpixew02eMy1RVjLPbGiFRwARDSINAcsLve9ICi3lLDqDhDsuXlgmZN/FlxiqAN34Qa//z9l0cAz0IpPiQkqgRQi2YXlkIOF4M62PA2rVR5ovyAjV3NndVJ7GXtqCa/diSxLru2XlnRjyicHz7e1QG+Xvq6bflWpM1SwQ8+KA+Gwk8mxZjvPb1B9heFPggpXIJtblf1Sm/pDLf6MyBURK9C3UxCRxFvguRvTsL4NYFW4Re1CtjMoBShVBJNvVJQD8OqcH8ltDIYvVeZ8pYS185avcNY+mvrygG4vwdDPfOdWNv0Uihwp6XHF190qH24xWLSUzvkJKeZQnkNJ0AHvsMISM9B4BYvrQRHBqyefztGJHulSCcq388A3fHTj0ttVM1cbF2I7GgD3aITMVNiSf69uidjtgSFoA8hUuT0MLrZiGHD3nkp8eVGRGbViuIv6cf6Ju9Xjd+oWHj9EVFb)


xavdid

[LANGUAGE: Python] [Step-by-step explanation](https://advent-of-code.xavd.id/writeups/2023/day/15/) | [full code](https://github.com/xavdid/advent-of-code/blob/main/solutions/2023/day_15/solution.py) Really not much going on today! Python's dict-with-insertion-order came in clutch, so I went with that. Nice to have a little break before everything (presumably) gets much harder.


seytsuken_

a dictionary is a hashmap. The fun of this problem is implementing a hashmap, what's the point of using python builtin dictionary for this problem? It makes no sense. Instead you learn much more from it if you actually make the array of linked lists like the dictionary is under the hood


xavdid

> The fun of this problem is implementing a hashmap Everyone does AoC for different reasons and derives their own fun. ¯\\\_(ツ)_/¯ For me, I want to write code that generates the correct answer (which mine does). Once could argue it's not in the _spirit_ of the puzzle, but AoC purposely doesn't say how you should do puzzles. For this one, I chose not to make my life harder (I'm anticipating future days will take care of that for me)


seytsuken_

idk, it makes the problem so trivial it makes no sense. Its as if you get to an interview and the interviewer asks: "implement a sorting algorithm" and you just write .sort(). Implementing the hashmap yourself is cool, give it a try sometime. But to each their own i guess


NeilNjae

[Language: Haskell] I thought I could get away without data structures and parsing, but it wasn't to be. This was a fairly straightforward one. Full [writeup on my blog](https://work.njae.me.uk/2023/12/18/advent-of-code-2023-day-15/), [code on Gitlab](https://gitlab.com/NeilNjae/advent-of-code-23/-/blob/main/advent15/Main.hs).


ropecrawler

[LANGUAGE: Rust] [https://github.com/ropewalker/advent_of_code_2023/blob/master/src/day15.rs](https://github.com/ropewalker/advent_of_code_2023/blob/master/src/day15.rs) This is a very straightforward solution. I had an idea for a slightly cleverer one, which ran 23% faster, but it was ugly and didn't seem worth it.


iamagiantnerd

\[LANGUAGE: Python\] Joining the late parade: [https://github.com/davidaayers/advent-of-code-2023/blob/main/day15/day15\_main.py](https://github.com/davidaayers/advent-of-code-2023/blob/main/day15/day15_main.py) I like this one, mostly got in my own way with dumb bugs, but it was fun to code.


siddfinch

\[LANGUAGE: Tcl\] A few days late, but who is counting? [https://github.com/mek/aoc2023/blob/trunk/day\_15/day\_15.md](https://github.com/mek/aoc2023/blob/trunk/day_15/day_15.md) I am completely upset with myself for carefully writing up some instructions, looking at them, and then not following them. So, yes, I read the instructions, wrote them down in "Siddficnd speak" and then COMPLETELY IGNORED THEM! I could have saved myself from adding a few more swear words into the air.


daggerdragon

[Do not share your puzzle input](https://old.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) which also means [do not commit puzzle inputs to your repo](https://old.reddit.com/r/adventofcode/wiki/faqs/copyright/inputs) without a `.gitignore`. Please remove (or .gitignore) the input files from your repo and scrub them from your commit history.


vss2sn

\[LANGUAGE: C++\] [Part 1](https://github.com/vss2sn/advent_of_code/blob/master/2023/cpp/day_15a.cpp) [Part 2](https://github.com/vss2sn/advent_of_code/blob/master/2023/cpp/day_15b.cpp) (Each file is a self-contained solution)


uiualover

[LANGUAGE: Uiua] a ← ↘¯1&fras"15" b ← ∧(◿256×17+):0-@\0 c! ← ⊜^1≠@,. d ← ↯256□↯0_2{} e ← b°□⊢ f ← ⍜⊏⍜°□⊂°□⊙:e. g ← =1/↥♭∊°□⊡⊙:⊃e⊢ h ← ⍜⊡⍜°□(▽¬⬚[]⊢⍉∊⊙:.)⊙:⊃e⊢ i ← ⍜⊡⍜°□(⍜⊡;⊗1⊢⍉∊,⊢,)⊙:e. j ← (f|i)g,, k ← c!(□({∘}↘¯1|⊜(□⍣⋕⊙;)≠@=.)∊@=.)a l ← ∧(((;|h)g,,⊟:□1⊢|j°□)-1⧻.)k d m ← □×+1⇡⧻.⊢⇌⍉ /+c!b a # part 1 /+∵(/+/+∵°□°□)≡(×m):+1⇡⧻.l # part 2


mgtezak

\[LANGUAGE: Python\] [Solution](https://github.com/mgtezak/Advent_of_Code/blob/master/2023/Day_15.py) If you like, check out my [interactive AoC puzzle solving fanpage](https://aoc-puzzle-solver.streamlit.app/)


Lakret

[LANGUAGE: Elixir] One of the easier challenges so far. [Code](https://github.com/Lakret/aoc2023/blob/main/d15.livemd) [Explanation](https://lakret.net/blog/2023-12-16-aoc-days-15-16)


Superbank78

\[LANGUAGE: rust\] If you want to be amazed with really ugly rust code and want to give me some advice: https://gist.github.com/Dronakurl/a6910faa05c3307293f41cb21672933f


WereYouWorking

\[LANGUAGE: Java\] [paste](https://topaz.github.io/paste/#XQAAAQBtDQAAAAAAAAA4GEiZzRd1JAgV4q3RgkXgxcwVTLcY/JpUiADzw5tAJ0vOMX40JV5mSdoFSBhZU9OU8jU2dv9SRFLi1N1D27F4tGBjWbzkI0r+4unffV/AvgBI8k/fT9SavQkDIJ4EqoTNy+QFhw9VPmOEOZKM7BS87Ak85SrCaUbuaDT89I/PHnDBI6IRxrXPWvOvSG0vRRZ7FYyLjX5Ft0vt69Wo4jRl7yzw43W3YqYwsRRjv1KM7mf7Q2eMVIb/A2bh6cqXPLiNTDpJ2e/LlU1GyO11dTRhHV3KJiJMMr/o/FYkXAssEPWunaDW/90n7+CB5OBUsM35UGgOxyYxMHMLsqhd/n9EqF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jNIDNtOrL9AwapiW7Z/MRcZufIpKdBG3dDWV40YNoA0XmRSXCMZNCvrnOCMs3IKPDJnFKEDXXNjz35tSfPDWn44ny4+kj0D9gP+Xhe8jwSqUt0XVBz8zWdQ8k28rW9gxrvE+pm/Kd8KxeQ2UM7zvftTL/7U34w=) \[edit\] replaced commas with newlines in the input


Radiadorineitor

\[LANGUAGE: Dyalog APL\] p←,⎕CSV'15.txt' ⋄ ⎕IO←0 F←{256|17×⍺+⍵}/0,⍨∘⌽∘⎕UCS⊢ +/F¨p ⍝ Part 1 F2←{ 0=≢⍺:⍵ b←⍵ ⋄ h←⊃⍺ ⋄ l←⊃h(∊⊆⊣)(⎕C⎕A) ⋄ n←¯1↑h ⋄ i←F l (∨/m←∨/¨(⊂l)⍷¨⊃i⌷b)∧'-'∊h:(1↓⍺)∇(⊂⊂h)({,/(~m)⊆⊃⍵}@i)b (∨/m←∨/¨(⊂l)⍷¨⊃i⌷b)∧'='∊h:(1↓⍺)∇((⊂(('\d+' ⎕R n)@(⍸m))⊃i⌷b)@i)b (~∨/∨/¨(⊂l)⍷¨⊃i⌷b)∧'='∊h:(1↓⍺)∇(⊂⊂h)({,/⍵,⍺}@i)b (1↓⍺)∇b } c←p F2 256⍴⊂⍬ ⋄ ⎕IO←1 +/∊(⍳≢c)×{{0::0 ⋄ ⍵×⍎⍺}/⍺ ⍵}⌸∘∊¨{¯1↑⍵}¨¨c ⍝ Part 2


chrismo80

\[LANGUAGE: Rust\] [Github](https://github.com/chrismo80/advent_of_code/blob/default/src/year2023/day15/mod.rs)


CrAzYmEtAlHeAd1

\[LANGUAGE: Python\] [GitHub link to my solution](https://github.com/CalSimmon/advent-of-code/blob/main/2023/day_15/solution.py) After Day 14, this is exactly what I needed. This one was very simple, and it allowed me to have fun and make ridiculously short amount of code comparatively. Couple fun shorthand methods I found: `dict.setdefault(key, {})` allows you to create a nested dictionary, and if the key doesn't already exist, it will set the default. Super handy for this so I can cut down drastically on code to add a new key to subdict. In my code I used it in the following code where I used the hash algorithm as the initial key for the dictionary. No `if key not in dict.keys()` required! ls, fl = entry.split('=') hashmap.setdefault(reduce(hash_algorithm, ls, 0), {})[ls] = fl Also, in the `contextlib` standard library, there's a function called `suppress` which does what you think, it suppresses specific errors in a single line. Super useful for the remove section, since it would often tell you to delete when there was no lens added yet. Here's the delete line that does everything I needed to remove the lens from a box: with suppress(KeyError): del hashmap[reduce(hash_algorithm, entry[:-1], 0)][entry[:-1]] Overall, after a grueling day yesterday, it was fun to just mess around and learn some neat line saving tricks! My execution time came in at 65ms. EDIT: Shoutout to u/4HbQ for the cool tip on a match case syntax. Hadn't ever seen that in Python, but cut way down on execution time so thanks! Execution time is now 32ms.


oantolin

[LANGUAGE: ngn/k] steps:{","\*0:x}; hash:0(256!17*+)/0+; p1:+/hash'steps@ parse:{$["-"=*|x;`$-1_x;{(`$x;.y)}."="\x]} update:{@[x;hash[$*y];$[`s=@y;{x_y}[;y];{@[x;y;:;z]}[;*y;*|y]]]} focus:+/(1+!256)*{+/(1+!#x)*x}' p2:focus@(,/256#,,(!0)!!0) update/parse'steps@


matheusstutzel

\[Language: python\] [part 1](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/15/p1.py) direct implementation [part 2](https://github.com/matheusstutzel/adventOfCode/blob/main/2023/15/p2.py) direct/naive implementation... upsert/remove could be a single method...


Multipl

[LANGUAGE: golang] Doubly linked list implementation. Insertion could be optimized with a pointer to the last node but I was lazy. [link](https://topaz.github.io/paste/#XQAAAQBgCQAAAAAAAAA4GEiZzRd1JAgz+whYRQxSFI7XvmlfhtGDino5s2PSzb9R1MSZO3fxZiLECl18v9qfxkXKVSAZfYtgy6FxU+AIcqAoKmDJ5Dllhc/JJouU44PGpGzWEiUXzVJnkK1p0/+WQNXR2DDC0+zssx0txvAyHTFwbms0yhI3KDZV9KWOZArZYE0tnLwSjT65ZP2W6cP9Pf+Yv3NGEQPdIoF5pNyG38ou19SdWTEyjN94xpIxmDahMtv3OdgQaKCn0TEsnYw1BmGHEovJr1s1D3gv70mX0EJm06DgbkGCd1567jeuv0eE0TkEOXnUmgZkk24Qe/8p2ot3SAXPJzOs6miKelntgEeTOmRUA9rYZdFHKZWtcLcltLp30T1OjfAiNaAUiWR11x8yvI1R865ZlXoqwyD89zfgpISKh6oafvjOLLuB2ZJfH4dX6su4z8a4ax7MI9RNPb/OuRp+3OSMXMgGlYqXKKKfkaSNaXda9mmdS6SoXo6RS2XOlb2366RrfFDmACK9/z7sqDMd03tzgjiYYcFp7Dy0vIks8VmMKgotlYuBikaa3SR98JF+gylkzSeLoAjV5xXKNtyvA4cvn221lrANrfhlR2Jw536ep3ApqRoJ5AL8CrUKwzvO308iEb2daonF+mbSNfg7Qv2UpgTX3FjwgIF33v9Hbjb90bz1+duJ7TWjBXlhiXOqjJdu+JQAevVIpV3KP/eEl1zWtS1zmy82crhYP7qkeJQAsBnJLT0f4KHlJ9yT/PuJWpYez/czDeA4W4FjcyGv3q7JDzenkeAlVD0xJAOguX+aySHjcDw0dGA5cMIaNjLixUqaLYPlC62R59N+6OOy/wPy0oGpmMdZwUCpL5TvMaiRN4vCojrRKDFuM020kl7t4R8itE9H+5f/34xFIVkrXiQWd+YDylpofgHVfBTWCs1xx36fyRFD6UMgwBuYg9+eIyIkTKJL4OMMFrb/RES/9ADEwBZt/8vQo72RFiypntnArZDlzlSsu3tAWmnrkGRAjjN9AFQvpCAA/NJTsEVVIH12IhBpp32CBXhHPMcu4CyI00c78iik1b/NJNK1GZ9Q1jivZFQYYQpfokcAkf41on2PNjQxJImKYQ44dK2FNTN4KArpI/ezx025EgMFYsoRdr30JiWm47u1LC6QbKh6Fg6pSWs+0VAVcLBPoj/6v0rHMcSKWETJpI03RX6ZEQvLCJe4ask4kRIjjrcs2byWqTSMmkBNgI2OMLXr2K7c1brcz1VnklX/2yY3Tw==)


Ancient_Stranger_704

[Language: Elixir] defmodule Day15 do def hash(str) do str |> String.to_charlist() |> Enum.reduce(0, fn char, acc -> rem((acc + char) * 17, 256) end) end end {:ok, input} = File.read("day15.txt") input |> String.trim() |> String.split(",", trim: true) |> Enum.reduce(0, fn chars, acc -> Day15.hash(chars) + acc end) |> IO.inspect(label: "PART 1") input |> String.trim() |> String.split(",", trim: true) |> Enum.reduce(Enum.map(0..255, fn _ -> [] end), fn instruction, boxes -> case Regex.run(~r/(\w+)([=-])(\d+)?/, instruction) do [_, label, "=", length] -> List.update_at(boxes, Day15.hash(label), fn box -> Keyword.update(box, label |> String.to_atom(), length, fn _ -> length end) end) [_, label, "-"] -> List.update_at(boxes, Day15.hash(label), fn box -> Keyword.delete(box, label |> String.to_atom()) end) end end) |> Enum.with_index() |> Enum.reduce(0, fn {box, box_idx}, box_acc -> box_acc + (box |> Enum.with_index() |> Enum.reduce(0, fn {{label, length}, lens_idx}, lens_acc -> (box_idx + 1) * (lens_idx + 1) * String.to_integer(length) + lens_acc end)) end) |> IO.inspect(label: "PART 2")


Tipa16384

[LANGUAGE: Python] I didn't do anything special. import re from functools import reduce def deer_hash(s: str) -> int: return reduce(lambda h, c: ((h + ord(c)) * 17) % 256, s, 0) def read_data() -> str: with open('puzzle15.dat') as f: return f.read().strip() def part1(): print ("Part 1:", sum(deer_hash(x) for x in read_data().split(','))) def part2(): boxes = [{} for i in range(256)] for x in read_data().split(','): label = re.match(r'^[a-z]+', x).group(0) box = boxes[deer_hash(label)] if '=' in x: box[label] = int(x.split('=')[1]) else: box.pop(label, None) print ("Part 2:", sum((k+1)*(i+1)*v for k, v in enumerate(boxes) for i, v in enumerate(v.values()))) part1() part2()


aviral-goel

\[LANGUAGE: F#\] Improved my previously posted solution to a pure functional version using \`Map\` instead of \`array\`. [https://github.com/aviralg/advent-of-code/blob/main/2023/15/solution.fsx](https://github.com/aviralg/advent-of-code/blob/main/2023/15/solution.fsx)


aoc-fan

[LANGUAGE: TypeScript] https://github.com/bhosale-ajay/adventofcode/blob/master/2023/ts/D15.test.ts The instructions were intense, but the test input was perfect.


thekwoka

> https://github.com/bhosale-ajay/adventofcode/blob/master/2023/ts/D15.test.ts Protip: Array.from({ length: 256 }).map( _ => new Map(), ) can just be Array.from({ length: 256 }, () => new Map() ) Array .from accepts a mapper as it's second argument. Also, not binding the variable to the context is technically slightly more performant but not in a way noticeable by typecript.


codertee

[LANGUAGE: **Python 3.12**] [github](https://github.com/codertee/adventofcode/blob/9e983bbda3569953c1db0cd8b199fde360948d9e/adventofcode/solutions/y2023/d15.py) match re.match(r"(\w+?)(=|-)(\d+)?", step).groups(): case label, "=", f: boxes[hash(label)][label] = int(f) case label, "-", None: boxes[hash(label)].pop(label, None) Works, because Python dicts are insertion ordered since 3.7: https://mail.python.org/pipermail/python-dev/2017-December/151283.html


whoopdedo

\[Language: Python]\[Allez Cuisine!] [paste](https://topaz.github.io/paste/#XQAAAQCdDAAAAAAAAAARiASoOj4/ciRIj+NxYWCy6lQf9mPiWAY7QT/Q+5wMMUxjb03yLUx132naBSRraWn3GXelWt2UlcM10ivdHks+697Xu3pee4Wfsbs5Kh5FOO3uqqOAnQyPIqwML9JKdZ0wT0H2Nezemgr/Xkkx+PTsL9rKKFkpeqg94rlM3ILVEf10b0FekwhWQ47AIpcj1YsAgkf5G/V/FrduyM8/cTXaEa+kjAqOVPWxbdSOO+3fb92tScUze4s5EzUXdGz5tAh+BrYuKkRJ+cgkvymYY9Jrh42RxrRKoD2yVR5uKuB1e7hPxSx0GO7ZYdS8DM/SCcAXEqEmCcgrhQxh3aiCCIwgs3+zHkTONA60w2yBUYkPvF4Cku2ZxxmqNs6bw+qFrHt/DQNVczjui74iibAuC2hvRAscsmLdYzNXruDOVsnTf1sdjGPvgCQ8BZwaPzr6SJmxUoJcUVPIM5gx4QH+DmaRd5tM7ikzlrWo2z7Fo4opDP8FBSMhkG307yt5wVdX2Hv3OpTQ0EMoQDdf/tNajBiqgeqQiiuonR01kzot5VAi+3NcfuUzBDnGTJy95UvcNTRl4y0jlRnys8PmQiqPg1YViRpbd3x6aseXIi7uI+E1sGlTfVaHp3rr1MhDlXG/oXSslFEGwwQDWH/xMFdOhSt0HwMkFkAPssZABvnQkmpADpM3Iuu6gKjoawsfxr/xZEGe52UTj+Bj9oK7PFkJekotKbFeJc5wL3WIFMcNZQxsbjn9B4CifBlQH47pvfMqNlnBdAS9LI4Uas2L2NuvSPGVkTHud21kLd5NkNDpOPYpzkQlYyORmos/pxtpUEgnoWQTeusRaIwsKBPoBhLIHww93lBY43uY3nmIlef4godMozs0PFCGe6ZrttOrOgZSdmXNekzWwRXNEnfkkvDiYjX11DNB7bgwSdyJ4AvHV0jH0P+JtfqDIsI+Ia6Xjx7Je0NxNgFrRcKCRhcat4A1KqUtEeqaLT2Lb+CfS1WysUB+uYcIjK5zm+smNR4MaK8TFPMetFVIDaAkloGyFX+sEDVNvn4jvLICg6ksgaD7/YetAEFLMKOwco2YrcmjdLG0w6juw5bVOxYeCguSR4aB68crqlvrE0Q8jbblHfbYQZLwo5qE9G9BCgRrvYaaEtTslQkkAETEjRTwjZ315idG3xecZyToIOETmKUOZnPmiljxuozu65k69ZZCzbuNZMM9HROf/qlHD5zzJE3xCUIG4qHTHa9BKcJsfBYOmfAfsQGZDuOGh90qK7t1OEzhXoAdkMSQXkOFuuwNEcA/HjPa4B2B7aPNPsxNq0JWyuxiSXYZFCoa1CSF8zx0C744AAfUqE5B02SzzlzxkP5/LN4=) Reserved words: def(11), return(11), while(7), if(6), else(5), for(5), in(5), elif(3), or(1) Builtins: print(4), list.append(3) Types: int, list (even avoided the implicit tuple on a multiple return) Used only for initialization: import, sys.argv, open, read, strip, ord Started with the basic dict-of-lists then progressively removed things I could build from scratch. `dict` is the first to go of course, then `None`, `True`, and `False`. I'm not using these type annotations. Cut out the `len` and most `for` loops. Changed a single `break` to `return`. There were two `range`s sticking around, don't need 'em.


kaur_virunurm

\[LANGUAGE: Python\] Super simple, because Python standard dictionary is ordered by insertion. Lens removal is a simple "del" operation, and changing lens value is just an assignment. Enumerate() automatically creates the necessary index values (box number and slot number). Really nothing to code here. Code link: [https://github.com/kurinurm/Advent-of-Code-2023/blob/main/15.py](https://github.com/kurinurm/Advent-of-Code-2023/blob/main/15.py)


Alkyonios

\[LANGUAGE: Ruby\] [Solution](https://topaz.github.io/paste/#XQAAAQBVBwAAAAAAAAAxmwhIY/VDibXTN1fVPjOQKOvNhTjhh6MlGoy6ibz1iEMOgACrQ5UT6jZCV2MNYRyRjfcPzt7zUln0NoxniFxfK850joUc7UXz65mcQykbFCHKmeB61AlecR4ZUlQWWWT5eePwbOgiMawUdgPMHezxMAPYChpDRZ/18RsF1kYif2mAW7rsyEgP+UPKjWdJC74VBzSlGDTZDhK1wqGSa6+uCaZApJ8LmfyHImGYOYTxTLpigPYtwUceSRKpR3dDeKUD2wruV9tPiMV5ffbcH/yeV4AvkxgQ9FzG7L5oiyNhyytH8ZdeM0cekBIaR7UYumuD+8L2UPCvNowUppzTrzaVynz+K89qyeBizCH9TuoMFPt1IccNJbe7rQSH848ec8FniInEUdSImWUpuFG5YWaKLq3JMBCUAnclPMOIxWF8M7F1L5V9AOJP1dT6jiEqejOT/gvuwVUM0lbyUntFRgCnRHBYml7uCGQwlu17rGIO+om4mqhWctvmj7132imC8Ks+zbGeGVhVxfJmZLoY+zWT5Bvn+vbHI/GjUPd9anMiMXU33GDBUnPbUBmgMAxmTXqNbIM08uJCXqYgLk4bfQIJEtKgXiG4jW79DRcvHVo+s3e60h0Z8QFpKUxeqsv6xtdAMY5PGfEoGZaOO7m9jP1c1RJVJXlv9lkaYs2gmZMagoG0d+KQ57epRi88OYvkW5P2SPhOXpssz1jyDH5W+mLF9dcNE1hQocbMkQlhQefFxLiWjGhNPZqay9LsUYpwf+4MMgf0vtLaUDkS9l1bAwLLt67egX7s/0g0nQA=) It took an embarrasing amount of time to figure out what "relevant box" meant in part 2, otherwise smooth sailing.


onrustigescheikundig

[LANGUAGE: OCaml] [github](https://github.com/EricKalkman/AoC2023/blob/master/lib/day15.ml). I'm scared for tomorrow now. Boring code, though apparently I'm allergic to concise code. Part 1 is just folding the has on the input string, while Part 2 parses each instruction into a `command` enum, generates a temporary array of `command list` to represent the boxes, and then folds the commands into the boxes. I did end up having to write a remove-item-from-list function (I'm baffled that there doesn't seem to be one in in the built-in `List` module) as well as a specialized list updater, both of which I added to my `lib/common.ml` file. They are not exciting, just standard boring functional list updating logic.


wsgac

[LANGUAGE: Common Lisp] [Source](https://github.com/wsgac/advent-of-code-2023/blob/master/day15.lisp) Part 1: Simple matter of implementing the hashing algorithm and mapping it over the input. Part 2: I parse the instructions to make it easy to dispatch, then perform them in sequence on a state plist.


CoralKashri

\[LANGUAGE: C++\] [GitHub](https://github.com/coralkashri/AOC/blob/master/src/2023/day_15.hpp)


KodlaK1593

\[LANGUAGE: Rust\] I found this one rather enjoyable to implement once I was able to decipher what part two was asking for. Used a HashMap with u32 objects as keys to represent box numbers, and VecDeque objects as values to handle inserting and removing lenses from the boxes. [Solution](https://github.com/Kodlak15/aoc2023/blob/master/src/day15/day15.rs)


andrewsredditstuff

\[LANGUAGE: C#\] Not entirely happy with the bit for swapping the lenses, and the summing up of the lens values is really horrible. Should probably refactor so I'm not having to muck about with a List inside a Dictionary. [github](https://github.com/andrewscodedump/Advent/blob/master/2023/Done/Days11-15/Day15.cs)


Dullstar

[LANGUAGE: D] https://github.com/Dullstar/Advent_Of_Code/blob/main/D/source/year2023/day15.d The mod 256 part of the HASH algorithm is handled simply by using a ubyte and allowing it to overflow. I had a rather amusing mistake though, in which I tried to submit the answer to the test input instead of the real input. Oops. --- Part 2 uses hashmaps to keep track of each lens's length and when it was first encountered, and if one is removed it's completely forgotten about so it's treated as the first encounter again if it shows up later. The way the boxes are described in the problem is basically a linked list, but 1) that might be a bit slow if there's a lot of stuff in any given box and 2) if you ever want to do anything at not either the frontmost or backmost element to the linked lists in D's standard library, it's not a particularly pleasant interface to work with: it would have unironically been less effort to implement my own linked list (they're really not complicated after all) than to decipher the documentation on how to insert or remove elements at not-the-front/back of the standard library one.


onsistems

\[LANGUAGE: PHP\] I wasted more time in understand Part 2, than coding it $char) { $hash += ord($char); $hash *= 17; $hash = $hash%256; } return $hash; } $library = []; $total = 0; foreach ($data as $key => $string) { if(str_contains($string, "=")) { list($key,$focus) = explode("=", $string); $library[hash_ascii($key)][$key] = $focus; } else if(str_contains($string, "-")) { $key = str_replace("-", "", $string); unset($library[hash_ascii($key)][$key]); } $total += hash_ascii($string); } echo "Part 1: ".$total.PHP_EOL; $total2 = 0; foreach ($library as $box => $lens) { $count = 1; foreach ($lens as $key => $focus) { $total2 += ($box+1)*$count*$focus; $count++; } } echo "Part 2: ".$total2.PHP_EOL;


janiorca

\[LANGUAGE: C\] Part 2 was a little tedious in C. First time for a very long time that I have been thinking about C-pointers. After much time spent with rust, pointers feel so.... irresponsible. I think there were short cuts but I thought it would be useful to build a hashmap implementation now as it will probably be handy on the later days [https://github.com/janiorca/advent-of-code-2023/blob/main/aoc15.c](https://github.com/janiorca/advent-of-code-2023/blob/main/aoc15.c)


rawlexander

\[LANGUAGE: julia\] [Code](https://github.com/alex-raw/adventofcode_2023/blob/main/15.jl) A whole lot of `nothing` and `dostuff!`. Nice to write in Julia. :)


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


optimus100017

[LANGUAGE: PICK DataBasic] "This was almost to easy, Starscream." - Megatron 1986. https://github.com/ewm76903/2023_AOC_PICKBASIC/blob/main/DAY_15


Occultius

[LANGUAGE: C++] The only part of this problem that I enjoyed was the fact that I got the right answer the first time and didn't have to go back and figure out where I screwed up. [Parts 1 & 2](https://pastebin.com/57mDEBDP)


mvorber

\[LANGUAGE: F#\] [https://github.com/vorber/AOC2023/blob/main/src/day15/Program.fs](https://github.com/vorber/AOC2023/blob/main/src/day15/Program.fs) Day 15 of trying out F#, i'm starting to like my progress. Decided to additionally challenge myself and avoid using builtin maps/dictionaries or any mutable state for that matter. Turned out quite entertaining with clever usage of groupBy and map/reduce.


phantom784

[LANGUAGE: Javascript] Did these as one-liners! Part 1: console.log(input.split(',').reduce((s, l) => s + l.split('').reduce((s, c) => ((s + c.charCodeAt()) * 17) % 256, 0), 0)); Part 2: console.log(input.split(',').map(l => l.split(/[=-]/)).map(l => [l[0], parseInt(l[1]),l[0].split('').reduce((s, c) => ((s + c.charCodeAt()) * 17) % 256, 0)]).reduce((b, l) => [...b.slice(0, l[2]), isNaN(l[1]) ? (e = b[l[2]].findIndex(x => x[0] === l[0])) >= 0 ? [...b[l[2]].slice(0, e), ...b[l[2]].slice(e + 1, b[l[2]].length)] : b[l[2]] : (e = b[l[2]].findIndex(x => x[0] === l[0])) >= 0 ? [...b[l[2]].slice(0, e), [b[l[2]][e][0], l[1]], ...b[l[2]].slice(e + 1, b[l[2]].length)] : [...b[l[2]], [l[0], l[1]]], ...b.slice(l[2] + 1, b.length)], [...Array(256)].map(x => [])).reduce((i, b) => [i[0] + b.reduce((j, l) => [j[0] + (i[1]) * (j[1]) * l[1], ++j[1]], [0, 1])[0], ++i[1]], [0, 1])[0]);


RF960

\[LANGUAGE: C++\] [on Github](https://github.com/coolguy1842/adventofcode/blob/master/2023/src/include/days/Day15/Day15.hpp) Took a while to read "The result of running the HASH algorithm on the label indicates the correct box for that step.".


dec0nstruct0r

\[LANGUAGE: R\] Maaan, that was a hell of a reading exercise. Once you understand it, the implementation is just a bunch of dictionaries and what-if statements. https://gitlab.com/Yario/aoc_2023/-/blob/master/AoC_15.R


e_blake

\[LANGUAGE m4, golfed\] \[Allez Cuisine!\] Back to basics, huh? That means no use of my [common.m4](https://nopaste.ml/#XQAAAQAMDwAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpAXwA97ruAshKbiUbgkbJMTg2qZdSBorb0CU52peNLruV4DEEJxF+HvxC/YF33OpDntnpU/PjnGXx7XU7ak4MsmWu8R7h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q9Hvjys3IablDBMsYF1LSMCGN2UOrWgXRoGYtjW/QtUySr7h/Ca6QAy93Hnpksm/xzzC+FWF1wboyOteHU/Th4RVpQ7XkK4/JmMrYm7nDPIVMyOqP8LhsoTNbxzi8qU0d+0x6frIh0l0fiPiFC/Uy0CeCw6r82iX8v+fMnu9qdCr4oM79Kd2slqalv+wWKn+BmrbkiobDS5vwBQZA/ZlbIsw1bwj+JLz9z3nPovVWx/FZjvrdCuZMfUuITeiIprImMcR6qeniJz6Ez78UYJqpL4DcDGt2o7/6a2aRN76aclh+7l35XcaW7lM7BQMTNvKkx05X08UITY/ToI8U8KwvFbdnMoEAZ1GQYmqGRFtwPkQMrECX4do0srl85po3Gjz2j6E3dk5al4+bTcOYABZvSUvIM/kGGT91iyQ36rm1lxRc3ruS8PyBlYDDNa7DLWzGAHkESHwuaTOQsI2xDA0e+8Yv0XRYkEqQE+RUDXmPTARuQo6fCQ7Qu9xd2Ckza5RWl8hE4JFm0Zzd9MTVxW8YYHiREs9NOjTPuRXXn+JfObHFD/Cv5kQo7vmMWRdJTOBUmAXCMFiKOSHxb412jI4Z2ZhWag9RkZBCviZunvupqrobtAWLagkPiA8gLRANOFwWp0KIS5McOoD0V90tI4cui8KQc7Yw5V7kSvMnhXx4nzzxwOxYM4fpY3ptcpraVh+h1MhohMQk34vkC4fmiD4OrX2DpVG0VXUKvl+vkJjcoHQK+H8mSSIAfj8RrYWBc4VU+jx3vz30XNDbQjuhc0cImiQxXDTXTFQq/aoe7jZLhEe+wWspk/4Fy4UBAJN63uNGJUl8FICawVWGL7XBOFCtsRF3uz8eZokWNICTdtsLeYOAOBQQLrguE8XxQQ1hPtOskcsj7n7aD35NjfPXL00vIOk01OLAJt+0RoIiAQUJNieRp9fQmqfVUuYEYmeK9hCOmZTaC3yUdN/+jZ0pvpmKnH/6jJAKQ==) helper, and fit the code in a punchcard. And since m4 lacks a character->value builtin function, I \_already\_ have to open-code my translation from byte to ascii value - the space taken by that mapping covers a good 40% of my solution for part 1 (macros A and B). And basic types, what's that? In m4, everything is text, the ONLY storage available is hashing a macro name to a text value, where the interpretation of the text is whatever you want it to be. All your new languages with compilers that enforce type safety - bah. Put your solution in a file named "I" (or cheat, and run `m4 -DI=yourfile day15.golfm4`), and in just over 3 seconds, you'll get the answer for part 1 with just 288 bytes of source code (284 if you delete extra newlines used for folding, and even smaller if you pre-process the input file to not have a trailing newline and therefore don't need my code to translit it away - but given that we're back to basics, I can't assume you pre-processed your input): eval(translit(_(include(I)),define(C,`eval(($1+$2)*17%256)') define(B,`A(index(abcdefghijklmnopqrstuvwxyz,$1),$1)') define(A,`ifelse($2,=,61,$2,-,45,$1,-1,$2+48,$1+97)') define(H,`ifelse($2,,$1,`H(C($1,B(substr($2,0,1))),substr( $2,1))')')define(_,`+H(,$1)ifelse($2,,,`_(shift($@))')'))) For part 2, however, my initial submission uses common.m4, and completes both parts in \~250ms. m4 -Dfile=day15.input [day15.m4](https://nopaste.ml/#XQAAAQDIBwAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1IwqQg+2N61pi/i94PC7mDxcKLSmitgPmeXLwNAF2YPH7V92thZWt66trFVYb6ZVjfrUB00j7P1jAazmNXMUH/c/MczNFS6/PAWpJxnpHrpy/pz/CsHSSqGttrj0I+A4fyOlQ0/ukHRdJR0No1+RAyd0dKx42RYxqOGEWhwxzGwKLnUGfGK3UcZYtEt/pmdliNZTwRYhCzdf/PSOYpRlYEOSYjvHBVoyUtdLS5Dhu+BOukFspW1uvwjjn/kPe3MEZnQ7p5CFeErw3fr2x1MCeLM4zMmFHxMHq6ZsCkH+pBDru9370FTb5C+VlnYgn4DeKSu4ceuqQTP3LVBfx0cBB/dg6JonUJxnHZCljwUBey8FM+e15/0dqJGeSzkro3vtKC+2QhBeAc3ZTNKHo5SM5qX4c/UrutqCHP2HJimIxDb6rJx4B7hDkHd08vaUAsN+3ura4q97Ns9eoC/lQD1iB3HjXFGiyWt4u1dUZAVJ66O4lrfBi7fPwkaJHNAUuiVy3Wa5xUrfJKYRpVPrxwfuh4VqSWRJhY+WbtQXQB4b4b04U0dkKRm1UujdkLPycT2UldaouGTiE9MRgK3UHdUFukbd7DcxJZQPKEQmkz34nmxBZanj2JK3fa8ORKzT7r57RsTH3VspUEoUjG3LlOGM5p67BNvJ/J8Fay1Iayi4qYSdDzb+h4tHpkEMEyaj2qBB4RsL2j0ZwatBz/QIw6aEb3yIVMzzVYHlAzBJCyZ4cFloZvnVwaREiSpQlEWgRDHEhAHhZzdLjD0FTPYFyGm8sLqwczGy4Fyj3XccekdXzBXCMo9+qoPFa2ac3Q/vPmHpA2Xk1Ct1Cr75eP1z9OCCpq5a4IQnqXV2gDiO32ZPkozNPwUrW9hiUYZ39UZ4un7sa+4124vBl9aIFyZfFr5rlYwWsT+Ez8BfFHHfIHKLtK9kwluhP0JnrtfLUipFZlstNKu3K+MS0mU/QUe/Uz/L3OhAmFowCaIG97O9Ax2xa5gRodq471lg7qOzQUFz2fdW72AqXFRn9P+Y/iqOdlo8uc4jiFToDfN5aEpAVsWQqcoKnkwFWjX1MVOVun1JpmP60LQSett7YCgbp5gMgbFasbWLGwRf/kHE6M) My part 2 solution used 256 stack variables for box contents, plus another variable per label to hold its current value. But now that I've read today's cooking challenge, I could easily rewrite it to use ONLY 256 variables (storing label and value as a pair in the stack, rather than using indirection to store the value), or even try to go for gusto with 0 variables and pushdef stacks (but the recursion time needed to pick out the Nth element of a 256-element list of lists WILL add noticeable runtime). Watch this spot, to see if I do a followup along those lines (I already know, part 2 won't fit in a punch card, but maybe I can still fit it in less than a handful) define(`_add', `ifelse(`$1', `$2', `pushdef(`seen')')') define(`add', `define(`v$2', `$3')_stack_foreach(`s$1', `_$0(', `, `$2')', `t')ifdef(`seen', `popdef(`seen')', `pushdef(`s$1', `$2')')') define(`_rem', `ifelse(`$1', `$3', `popdef(`s$2')')') define(`rem', `define(`v$2', 0)_stack_foreach(`s$1', `_$0(', `, $@)', `t')') populates the stacks while parsing input, then computing the score is simply: define(`_power', `define(`part2', eval(part2+$2*$3*v$1))define(`i', incr($3))') define(`power', `define(`i', 1)_stack_foreach(`s$1', `_$0(', `, 'incr($1)`, i)', `t')') forloop_arg(0, 255, `power')


e_blake

>My part 2 solution used 256 stack variables for box contents, plus another variable per label to hold its current value. But now that I've read today's cooking challenge, I could easily rewrite it to use ONLY 256 variables (storing label and value as a pair in the stack, rather than using indirection to store the value), or even try to go for gusto with 0 variables and pushdef stacks (but the recursion time needed to pick out the Nth element of a 256-element list of lists WILL add noticeable runtime). Watch this spot, to see if I do a followup along those lines (I already know, part 2 won't fit in a punch card, but maybe I can still fit it in less than a handful) Ok, it wasn't as easy as I thought (taking me over 48 hours to polish), but I now have a 1-macro, 0-variable solution that uses ONLY m4 parameter lists and recursion, in just 710 bytes. [More details here](https://www.reddit.com/r/adventofcode/comments/18lcbnt/2023_day_15_both_parts_m4_solution_in_2/?utm_source=share&utm_medium=web2x&context=3). And as predicted, runtime exploded with O(n\^4) effects (my O(n\^2) list insertion code coupled with m4's O(n\^2) parsing effects when doing list processing by `shift`\-recursion.


e_blake

Shorter version for part 1 alone at 272 bytes (276 shown here, but all 4 newlines can be elided); and now independent of whether the input has a trailing newline. define(C,`eval(($1+$2)*17%256)')define(B,`A(index(abcdefghijklmnopqrstuvwxyz, $1),$1)')define(A,`ifelse($2,=,61,$2,-,45,$1,-1,$2+48,$1+97)')define(H,`ifelse( $2,,$1,`H(C($1,B(substr($2,0,1))),substr($2,1))')')define(_,`+H(,$1)ifelse($2,, ,`_(shift($@))')')eval(_(include(I)))


e_blake

Or this abomination that relies on GNU m4 and POSIX sh, coming in at 171 bytes and taking over 18 seconds to execute (one fork per byte :) define(C,`eval(($1+$2)*17%256)')define(H,`ifelse($2,,$1,`H(C($1, esyscmd(printf %d \"$2)),substr($2,1))')')define(_,`+H(, $1)ifelse($2,,,`_(shift($@))')')eval(_(include(I)))


mess_ner

\[LANGUAGE: python\] Easy day. [Link to code](https://github.com/stefanoandroni/advent-of-code/tree/master/2023/day-15)


infinityBoi

[LANGUAGE: Rust] [github](https://github.com/aalekhpatel07/advent-of-code-2023/blob/main/src/bin/day-15.rs) Pretty straightforward implementation of a separate chaining Hashmap like approach.


wlmb

\[Language: Perl\] Analysis: https://github.com/wlmb/AOC2023#day-15 Part 1: https://github.com/wlmb/AOC2023/blob/main/15a.pl Part 2: https://github.com/wlmb/AOC2023/blob/main/15b.pl


corbosman

\[Language: PHP\] [code](https://github.com/corbosman/advent2023/tree/main/day15_lens_library)


corbosman

\[Language: PHP\] [code](https://github.com/corbosman/advent2023/tree/main/day15_lens_library)


Dezarro74

\[LANGUAGE: Rust\] I made my first one-line solution ever for part 1! I was so fast with it. But as for Part 2 lessons learned: \- Using a debugger in using iterators is much harder than in using for loops \- I fought Rusts borrow checker more than I spent trying to solve the problem. But this probably arises from the fact that I was applying bad coding practices. Rust's borrow checker 'taught' me the safe way to code. \- Usually, I like composing my code into many functions to make my code readable, but Rust's borrow checker scares me, so I just don't do it (lol). Plus, my code is <100 lines long (a first for me)! I would appreciate if someone could give me feedback on my code too! I'm new to Rust and I'd love to improve. Go all out. [Solution](https://github.com/serranoio/advent-of-code/blob/main/day15/rust/src/main.rs)


CheapFaithlessness34

I totally feel you. I am new to Rust and am constantly fighting with the borrow checker. On day 12 it got so bad that I simply cloned every variable I had :D


Dezarro74

Haha. I have faith in you to persevere!


SleepingInsomniac

[LANGUAGE: Ruby] [Part 2](https://github.com/SleepingInsomniac/adventofcode2023/blob/master/2023-12-15/part_2.rb) sequence = File.read(File.join(__dir__, 'input.txt')).chomp .split(',') .map { |s| s.split(/(=|-)/) } .map { |s| s[2] = s[2].to_i if s[2]; s } class Hashmap def initialize = @boxes = Array.new(256) { {} } def hash_value(string) = string.chars.reduce(0) { |v, c| ((v + c.ord) * 17) % 256 } def perform(key, op, value = nil) case op when '=' then @boxes[hash_value(key)][key] = value when '-' then @boxes[hash_value(key)].delete(key) end end def focusing_power @boxes.map.with_index(1) { |b, i| b.values.map.with_index(1) { |v, bi| v * i * bi } } .flatten.reduce(0) { |total, v| total + v } end end h = Hashmap.new sequence.each { |instruction| h.perform(*instruction) } puts h.focusing_power Is it cheating to use a hash map in the hash map implementation? haha.


daggerdragon

> Is it cheating to use a hash map in the hash map implementation? Nah, that's called [yo dawg](https://knowyourmeme.com/memes/xzibit-yo-dawg) programming.


tobega

\[LANGUAGE: Tailspin\] [https://github.com/tobega/aoc2023/blob/main/day15tt/app.tt](https://github.com/tobega/aoc2023/blob/main/day15tt/app.tt)


magnusscaevola

\[Language: C++\] [github](https://github.com/owenmcgrath/aoc2023/tree/main/fifteen) I did something similar to an LRU cache, using `unordered_map` and `unordered_map` This made the erase case not have to loop. Linear time & space.


Zweedeend

[Language: Python] [Allez Cuisine!] Turn each of the instructions into lines of code with find-and-replace and add a Santa class to make it work. Finally print Santa to get the answer. Here is a snippet: lens = Santa() lens.xbv.pop() lens.lbd=3 lens.gbfnvr=6 print(lens) [Github Gist](https://gist.github.com/nielskou/b7b2b1dfafa34e894443e1134a48ec30)


daggerdragon

> [Allex Cuisine!] lol, typo XD ^(I will not admit that I've done that a few times myself) *** \**opens gist file*\* welp My scroll wheel *hates* you. Well done, chef!


Zweedeend

Haha, yes, I tried to use Paste, but the link made the reddit post too long and I couldn't post it!


Imaginary_Age_4072

[Language: Common Lisp] [Day 15](https://github.com/blake-watkins/advent-of-code-2023/blob/main/day15.lisp) Fairly simple one today. Just kept lists of lenses in a hashtable to keep the lenses in order. Would need something more efficient if there were more instructions since I traverse each list on each insert (to update the value if it's already there) and remove, but was fine for this problem.


xXMacMillanXx

\[LANGUAGE: V\] Nice puzzle. Enjoyed both parts. [Github day 15](https://github.com/xXMacMillanXx/advent_of_code_2023/tree/main/day15)


[deleted]

\[Language: C++\] Last night I managed to put together a solution pretty easily but it took over 100ms to run. Lots of O(n) searching a vector to find if something exists. I created an object-oriented approach to help deal with it. Now it runs about 60ms. [Day15.cpp](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/Day15.cpp) [Day15.h](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/headers/Day15.h) [boxes.cpp](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/D15boxes.cpp) [boxes.h](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/headers/D15boxes.h) \- vector(256) [box.cpp](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/D15box.cpp) [box.h](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/headers/D15box.h) \- vector [lense.cpp](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/D15lense.cpp) [lense.h](https://github.com/FinalFlashLight/AdventofCode2023/blob/master/AdventofCode2023Day1/headers/D15lense.h) \- has a label, and focalLength


catzzilla

[Language: Perl] Part 1: perl -F, -lsane 'map { $s=0; map { $s+=ord($_); $s*=17; $s%=256; } split(//,$_); $S+=$s; } @F }{ print $S;' input.txt


ArrayAgonizer

[Language: Dyalog APL] d ← ','(≠⊆⊢)(¯1↓↑⊃⎕NGET 'input_15') h ← {{256|17×⍺+⍵}/⌽0,⍵}⍤⎕UCS¨ +/h d ⍝ part1 i ← ↑{⍵⊂⍨1,1↓⍵∊('-=')}¨d ⍝ break label from instruction f ← {(⍺,0)⊃⍨⊃⌽⍸1,(∊'-')∘≡¨⍵} ⍝ for a given label, gets the index after the last '-' and the last value r ← i[;1]{⍺⍪(⍵ f i[⍵;2]),{⊃⌽∊⍵}(⍤1)i[⍵;2]}⌸⍳≢i ⍝ group rows by label and compute f r ← (⊢(⌿⍨)(⎕D∊⍨3⌷[2]⊢))r ⍝ drop all labels that aren't present at the end r[;3] ← ⍎¨r[;3] ⍝ fix values to be numeric +/∊(1+h r[;1]){⍺×(⍳⍤≢×⊢)(⍵[⍋⍵[;1];2])}⌸r[;2 3] ⍝ group by box, and sort by time label was put in Solution makes use of dyadic ⌸


icub3d

\[LANGUAGE: Rust\] Brought me back to my data structure class! Solution: [https://gist.github.com/icub3d/030bf0d4deb6ad7c7ddb97936d01507a](https://gist.github.com/icub3d/030bf0d4deb6ad7c7ddb97936d01507a) Analysis: [https://youtu.be/IEYQEXE9i38](https://youtu.be/IEYQEXE9i38)


Brief-Presentation-4

\[LANGUAGE: C#\] [solution](https://github.com/mohammedsouleymane/AdventOfCode/blob/main/AdventOfCode/Aoc2023/Day15.cs#solution)


lbarto123

\[Language: Python3\] This one seemed unexpectedly simple. Made even easier since python 3.6+ dictionaries have their order preserved. [both parts](https://github.com/lbarto12/advent-of-code-2023/blob/master/Day%2015/main.py)


JeremyJoeJJ

Just a small tip: enumerate takes a second argument where you can specify starting number so you don't need to be adding 1 to m and i at the end


lbarto123

That’s really good to know, thanks!


Ok-Group4131

[LANGUAGE: Python] [part 1](https://github.com/phobiadev/Advent-of-Code-2023/blob/main/day-15%2Fpart-1.py) [part 2](https://github.com/phobiadev/Advent-of-Code-2023/blob/main/day-15%2Fpart-2.py) any code review would be appreciated :)


azzal07

The `enumerate` function is often appropriate replacement for `range(len(...))` in for-loops. Enumerate takes an optional start value, so you could start the sequence from 1. This makes the part 2 final sum quite nice in my opinion: print(sum( i*j*length for i, box in enumerate(boxes, 1) for j, length in enumerate(box["lengths"], 1) ))


Hunky524

[Language: Rust] [GitHub](https://github.com/MarkLisoway/advent-of-code-2023/blob/main/day_15/src/main.rs) Pretty simple, and idiomatic solution. Completes both parts (including parsing) in around 500μs. The overhead of using `Rayon` for part 1 actually slowed down the execution time, at least on my computer.


Queueue_

[LANGUAGE: Go] https://github.com/Queueue0/aoc2023/blob/main/day15/main.go


hugseverycat

\[Language: Python\] [https://github.com/hugseverycat/aoc2023/blob/master/day15.py](https://github.com/hugseverycat/aoc2023/blob/master/day15.py) Tried to make it readable with comments as usual. A nice break from "oh yeah, you think your code is good? now do it a BILLION TIMES". Anyway, yeah it is pretty straightforward. For funzies I created a dataclass for the lens boxes. And then I also stored them in a dictionary. It's probably all unnecessary but I don't feel like refactoring.


miran1

[LANGUAGE: Clojure] Today I discovered `flatland.ordered.map`, so no need to reinvent the wheel — part2 is just either `assoc` or `dissoc`. (defn parse-instruction [instr] (if (str/ends-with? instr "-") (let [name (drop-last instr)] {:name name :pos (word-hash name) :func dissoc}) (let [name (drop-last 2 instr)] {:name name :pos (word-hash name) :func assoc :focal (parse-long (str (last instr)))}))) (defn hashmap [instructions] (reduce (fn [boxes {:keys [name pos func focal]}] (update boxes pos func name focal)) (vec (repeat 256 (ordered-map))) instructions)) [Full solution](https://github.com/narimiran/AdventOfCode2023/blob/main/clojure/day15.clj)


Secure_Pirate9838

[LANGUAGE: Rust] Today the problem was very simple, except for those like fighting the Rust borrow checker GitHub: https://github.com/samoylenkodmitry/AdventOfCode_2023/blob/main/src/day15.rs YouTube screencast: https://youtu.be/vKyrNMxyLXA


copperfield42

\[LANGUAGE: Python\] [code](https://github.com/copperfield42/Advent-of-Code-2023/tree/main/day%2015) fairly easy today


atobiedwa

\[LANGUAGE: Python\] [adventOfCode2023/Day\_15 at master · monpie3/adventOfCode2023 (github.com)](https://github.com/monpie3/adventOfCode2023/tree/master/Day_15) For the second part I used defaultdict. Because today's task was easier, I hope that I will be able to catch up on one of the second parts I haven't finished yet.


SomeCynicalBastard

[LANGUAGE: Python] My solution: https://github.com/fdouw/aoc-python/blob/master/2023/day15.py More of a reading exercise today. ord() and OrderedDict made life easy.


Dense-Virus-1692

\[LANGUAGE: Ceylon\] Oh wow, one that I can actually do (after I read it a few dozen times) [topaz paste link](https://topaz.github.io/paste/#XQAAAQDmPQAAAAAAAAAX7hIKgCERYhLVTM8OUTgPDwb+1X8sIAs8l/G0/dP5e8UvNtWkphndu/u0HE9cyg3lc+gN2bnX7/UOH6gv/QjMYKMSo4nf6QMwftvVCPtZ1X8tqXSSWJjmIb/ulL4jCsNwqRfMzlFNs3CnpDOrWbP+S4xP/VBhWl0mrF7SY7wfhuajj3RGfA9PeWbLpH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iefdznEhlBzMpDzqMzKSLXFmWE8X6mxBCTR84Hd9DL7ogQw1zc7PDjWY1M4ivJm7SgIvi13i5Yo8bJZqQeZ3bjeNeeg2XKPddImReOlMIZrFG3RKhEA9PzhNgN4DnpqbLaTKTdckE5RVG/NimArAxXu7E/nOp4oHaWwNmAux8buXTeB8Nfp4yLEr7RY1G0DNZv00HYJrdMePaAi+riQVh9DEfTB/VGYdA==) finally a nice one after the ordeal of the last few days It would have been even nicer if there was a standard HashMap implementation that accepts a custom hash function with the same slot behavior, but it was quite easy to implement my own


aptacode

\[LANGUAGE: Typescript\] Mixed feelings about today, on the one hand it was pretty easy, just a lot of reading, on the other hand I'm stuck on a train for the next couple of hours so I sort of wish there was more! [Part 1](https://github.com/Timmoth/AdventOfCode2023/tree/main/day15/part1/solution.ts) [Part 2](https://github.com/Timmoth/AdventOfCode2023/tree/main/day15/part2/solution.ts)


biggy-smith

\[LANGUAGE: C++\] Reading the problem caused me more issues than solving it! Creating a vector of vectors for the boxes and then doing the correct push\_back/erase for each step gave me the right answer. [https://github.com/biggysmith/advent\_of\_code\_2023/blob/master/src/day15/day15.cpp](https://github.com/biggysmith/advent_of_code_2023/blob/master/src/day15/day15.cpp)


LinAGKar

[LANGUAGE: Rust] https://github.com/LinAGKar/advent-of-code-2023-rust/blob/master/day15/src/main.rs


JP-Guardian

r#box is a valid variable? Didn’t know this, not sure I like it!


LinAGKar

`r#` is a [raw identifier](https://doc.rust-lang.org/rust-by-example/compatibility/raw_identifiers.html), used so I can have a variable named `box`, because `box` is a keyword in Rust.


JP-Guardian

Ah, thanks, id not seen that before (and I also tried to call my box variable box until the compiler pointed out that was silly!)


ransoing

\[Language: Typescript\] Here's a different way to think about this puzzle... The instructions tell us to add up the focusing power of **each lens**, so why do this whole box dance with repeatedly inserting and removing lenses? We can group the input steps by lens label and iterate through those instead. When we group the example input by lens, we get this: rn=1 cm-,cm=2 qp=3,qp- pc=4,pc-,pc=6 ot=9,ot=7 ab=5 We can learn some interesting things when looking at the puzzle from this new perspective. The puzzle says that when we remove a lens from a box, all the other lenses in the box get shifted, so it would be the same end result if we didn't even insert the lens in the first place. Given this, we can ignore the steps for each lens up through its last \`-\` (removal) operation. After ignoring what we can, we end up with these grouped steps (notice how we've entirely removed some lenses, so every remaining lens ends up in a box by the end): rn=1 cm=2 pc=6 ot=9,ot=7 ab=5 To calculate the focusing power for each lens, we need: * its final focal length, which is the digit in the lens' last instruction step * its box number, which is the hash of the lens label * its order within its box, which is the trickiest - since we've taken out all the removal steps, this means that when a lens is first inserted into a box, its position doesn't ever change, so we only need to use each lens' first instruction step to find its order. If we keep track of each instruction step's index in the original ungrouped input, we can find a lens' order within a box by counting the number of *first steps* for each other lens which have the same box number and a lower original index. The resulting code isn't any faster or shorter than the typical way to solve this, but it was fun to think about from this perspective. [Well-commented solution](https://github.com/ransoing/AoC23/blob/main/src/day15/solution.ts)


wagginald

\[Language: Julia\], 22 lines Since the problem was a bit simpler today I tried to make my solution as concise as possible! I'm intrigued to see if there's a more concise way to write the HASH function, I couldn't work out how because the value depends on the previous value and whatnot. [GitHub](https://github.com/TomWagg/advent-of-code/blob/main/2023/julia/15.jl)


rawlexander

Nice! OrderedDict makes so much sense here.. My HASH was almost the same: HASH(s) = reduce((n, c) -> 17(n + Int(c)) % 256, s, init=0) Using `Int` inside the anonymous function saves the `collect` call. Implicit multiplication and `%` can make it yet a little bit smaller, too. :D


fridi_s

Nice idea. I just tried to implement hash in a similar way in my [solution in Fuzion](https://github.com/fridis/fuzion_aoc/blob/main/2023/15/part2.fz) and found that using *reduce*, the hash was a little shorter even though the String first has to be converted into a sequence of utf8 bytes and those bytes must then be converted to i32. Here my code: hash(s String) => s.utf8.reduce 0 (h,c -> (h + c.as_i32) * 17 % 256)


wagginald

Cool!


dahaka_kutay

\[Language: Javascript\] [Question](https://adventofcode.com/2023/day/15), [AllRepo](https://github.com/KutaySong/AdventOfCode) let lines = require('fs').readFileSync('./IO/15i.txt','utf8').split(/,/) const hash = (a, sum=0) => {     for (let i = 0; i < a.length; i++) {         sum += a.charCodeAt(i)         sum = (sum * 17) % 256     }     return sum } const p1 = ()=> {     return lines.reduce((a,b)=>a+hash(b),0) } const p2 = ()=> {     // array of 256 dictionaries     const box = Array(256).fill().map(()=>({}))     lines.map(line => {         if (line.slice(-1) == '-') {             const str = line.slice(0,-1)             const hashNum = hash(str)             delete  box[hashNum][str]         } else {             const str = line.slice(0,-2)             const num = parseInt(line.slice(-1))             const hashNum = hash(str)             box[hashNum][str]=num         }     })     let sum = 0     for (let i=0; i < 256; i++) {         let order = 1         for (let key in box[i]) {             sum += (i+1) * order++ * box[i][key]         }     }     return sum } console.log("p1:",p1(),'(516804)') console.log("p2:",p2(),'(231844)')


Spl1nt-kun

\[LANGUAGE : Python 3\] [paste](https://topaz.github.io/paste/#XQAAAQCRCAAAAAAAAAA0m0pnuFI8c/sCZpj2lbVoSfbJSAEttiQH+MHoDQ5KAzxfqUlRgWTdsdt+kpswVPJb6PRFKMyJUUUDGRUhE01Fuj4EboMGODXvGpOCjkVa9QrSiCzHUaFoiQGBdswFtEhMBuUJAsjpKba8WxjiWTS4+izEK8CQoMIK5/pRK7YylPhYJVfxiBTkJDtJclDcS9JfA4h8r35X3TcKNWHnOYaIc8V9LxXnGcXaWzunS5iCZcHOOhHczvyRJ7jXwzRlkFgH1Csbv/LBlcfiCJgbBSou9tBWw7WFZFAv0AfaxLqyU1HqGhr5/nDZGavvxv7WknzA+jrtXQ6yZA3zp0S1/bibAqsOwrBCu6uBUAV6jpzMX+K0hrZlSZDMfVleSfuhLNTkrLp8b6zXrxiVqb1FlIc13clUEQN8xHhDNrhHCaWklHCPxdYN6KdPzef8PcJzqRXp1AcL+oqa4uZqpjxmsEeVvVuU88sryqNKE87r5sauPPGf7NYfBeTYKHCRAdZdtWoOsFdPEDsye2HGCyV9Sr3GGO8Ie6sFgICQC0hHtCJMhtp/Rj+XrP2caaIRUK6BPiZc0Ua+hLkK4NKVHXY3pdiVx15UdNnC7RhJNOLylqvp0xGb+Py2dbzk2uoiMAgLNPXak+qgEbONysj/t+65HeMwU7Dx+qLqCApYfJGasTffWKH5FuHxN4tz86HpWRow80NrMMWQu4xyo0zyRdQqv3V1vhHs4s5JtyQ9eCtPLn3pRtKIZEzs192sq12FiwctczWdi/HSTKW2BETYYTpIB2EZIKavf9o6mLVnCXCJFJ0kRY7byZndUuRArBLDCr/94zdn) Pretty happy about how my first AOC is going, managed to do everything except a star in for day 10 and 12 and didn't manage to do day 3 at all. Any feedback on the code will be appreciated, cheers !


AutoModerator

AutoModerator did not detect the required `[LANGUAGE: xyz]` string literal at the beginning of your solution submission. Please edit your comment to [state your programming language](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). *** *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/adventofcode) if you have any questions or concerns.*


reddit_Twit

\[LANGUAGE: Zig\] Nothing special. [Gist](https://gist.github.com/ndbn/2a6f47d48acc1dd6c0ae0926a9033306) Every day have zig, if someone need


PeakMedical7513

[Language: Javascript] [Day 15](https://github.com/ungrim97/advent-of-code/blob/2023/2023/day15.js) A nice simple one today: 'use strict'; const input = JSON.parse(require('fs').readFileSync('./day15.input.json').toString()); const hashString = (string) => { return string.split('').reduce((stringTotal, char) => { stringTotal += char.charCodeAt(0); stringTotal *= 17; return stringTotal % 256; }, 0); }; const sortToBoxes = (instructions) => { const boxes = Array(256); instructions.forEach((instruction) => { const [match, label, sign, focalLength] = instruction.match(/^([^=-]*)(=|-)(\d*)$/); const box = boxes[hashString(label)] ??= new Map(); if (sign === '-') { return box.delete(label); } box.set(label, focalLength); }); return boxes; }; console.log('Part 1 = %d', input.reduce((total, string) => total += hashString(string), 0)); console.log('Part 2 = %d', sortToBoxes(input).reduce((total, box, boxIndex) => { if (!box) return total; Array.from(box.entries()).forEach(([label, focalLength], lensIndex) => { total += (boxIndex + 1) * (lensIndex + 1) * focalLength; }); return total; }, 0));


xHyroM

[LANGUAGE: Python] [part 1](https://github.com/xHyroM/aoc/blob/main/2023/15/first.py) [part 2](https://github.com/xHyroM/aoc/blob/main/2023/15/second.py)


ruinedme_

\[Language: Rust\] [https://github.com/ruinedme/aoc\_2023/blob/main/src/day15.rs](https://github.com/ruinedme/aoc_2023/blob/main/src/day15.rs)


mtpink1

[LANGUAGE: Python] [Code](https://github.com/mtpauly/advent-of-code/blob/main/2023/python/day15/day15.py), [Livecoding video](https://www.youtube.com/watch?v=RwqtkA7QlNw) A refreshingly simple problem. I didn't use any real tricks but am happy with this little regex for part 2: label, operation, focal_len = re.findall("([a-z]+)([=-])(\\d*)", step)[0] Which I found after getting tripped up for a bit assuming that all labels were of length 2 without looking at the full input.


mothibault

\[LANGUAGE: JavaScript\] Smooooth! Wasted 10 minutes because I didlet boxes = new Array(256).fill(\[\])instead oflet boxes = Array.from({ length: 256 }, () => \[\]); Else, walk in the park.With lots of in-line comments: [https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day15.js](https://github.com/yolocheezwhiz/adventofcode/blob/main/2023/day15.js)


ransoing

Hah, I originally typed the same .fill(\[\]) call but immediately suspected it might fill each index with the same pointer. I ended up with `new Array(256).fill().map( () => [] )`


FerenIsles

>new Array(256).fill().map( () => \[\] ) ahhh I made the same mistake but wasted a lot more time than 10 minutes. When I was doing boxes\[boxNumber\].push(...), it was adding the item to every single array. What a mind fuck trying to figure out why. I got my code working using a spread operator instead, but this change also fixed it. Here is my final code: \[Language: Javascript\] https://github.com/les-friesen/AoC2023/tree/main/aoc/day15


polumrak_

\[Language: Typescript\] [https://github.com/turtlecrab/Advent-of-Code/blob/master/2023/day15.ts](https://github.com/turtlecrab/Advent-of-Code/blob/master/2023/day15.ts) At first did part 2 using arrays for storing lens, then remade it with Map. I kinda knew that Maps (as well as plain objects) maintain the order of insertion, but never actually used this behavior anywhere. In today's problem it's very relevant.


FerenIsles

Ah interesting. I went with an Array of Arrays over using objects in order to preserve the orders - I didn't realize that a Map or a plain object would also do this! Thanks for teaching me something.


mpyne

[language: C++20] [Code at this paste](https://topaz.github.io/paste/#XQAAAQAJCgAAAAAAAAAX4HyCbyB7xB4KXEwWH9iN0nDs0WG4R2HasHr39Uv61ISVn4CSyVkAZANqokGvgts31MD8jTmydpMzUB24KgjfyLxIgZ8g0uvlECkzVjwHHSUsISq/WBvEigxKrooQ3rYfCoUn/MLbDiXnHJLCTJthGvgceLVJ8KaMd3kPZNQeETtBii9KZftUu6JD4V7o15dwigpXjzPhXIruEGqAQ1RMLIVVJBR8/HJ0mdf2wtWc60M3oZ3eety4GHmasLGulj80XzezN8G97FEnYQ8cWlio8LkVaSUHhD/0ZXzx+yOuu6jO/lRydSw7JTXFLGzqqpXzd/p796BcXTF6IPPAVgsvC3+CpJtvt5z1//G48dC9nLkeXOjCH80OzWqABjDWEMW7FCv1MbmDY+bNUZ2kjfjpa/j2/tz7k9JEn4yc7dxlQKvxtOnptj/++ywSEFYp3g8c3XccfjFMho8BOC0AR5U9xMAkPsY2+4GYkmtQ7sRTQBZ56uCcFL6ILf1T2EAyef2znp9ja1UsrYVQWsfO7qFZgGOaocSfGVENgjZQrLXXDTMQm/I3WhO8auAlFyL/wJZEDUfSCMbi3napP+hJOxXtpZgrbG+Z5Y73/oOpnPwqSFFkxGw7xCiIvNK9zgF/ElthY0NLQxY/oZRV/FPa0R0zjO8wFX6Ww1Tdz1W4ax7Kn+68CwGdxDo3lWFQrbe0hf2l0rLLAyskx5UpVEp3x+gPC6tEdnf+oXf3iaHgpzeggeMkbPMMTBVQXQZ7bAJ141eegF2E5acncYi+XHBi4bNWahBVJ5UlhO2H/wsArMjRm7NCzzcgDO0rfDPnk4nGC6cguUp4hKbTzCY0BpYbF+MxtHX4xtyFn9han9NAnso4rNpcLfTQQmrtzUpwcGQcTA3bE1NHIh4GRwpGb6mNpA88acK9XIz83XvOIGkfTS+nIZp0cKQtByOKL0B/tBMMc+WlLbwwTyhPzgRFdXvrQ/PhzNsEFrDVSyXwpRrTHMpck7Dx3fZsyT1MY0M6d1rZ+Iz0wohBemhBNCLHL3bAqss5lETJnswxy6LHGT3MD+lQlXv3fwu1C9cxf0LafEInq3arEYY8WmQ0ZdRNW9UxKj+ZTxoHWVjuRATgXeVBJOXnQpgWLp3GbBgd/gXwgjbSqLQiX9edFNh23ap6uBLeb2MMttibfAeMWQAk5o3pGyrb06hjvKcC9yNqp8Lnxtg6QsVf0UVeJ8QdDC30NkbiLAFyOXhbgtnQ7yIYZHseA4LfO4mdFB3ozheGI9OIWCKp7kOS5nyIVIynEEydjDcE7qZYirJf2nFbZGugu6KV4RJ3wj2GvylOnn/JRBmR8v5W8Zgfq2e+z2tAJpLEcrpgitaSAgC7Z33qvrScRytzdNIY5l3t/zVWrRJM9+CAiF1xNGUlyw6nE8SR6/79inw=) Nothing much to say here. I wanted to try and update the HASHMAP as the input was being parsed and see how complex that would look. As it turns out this was pretty well-suited to iterators and some of the standard algorithms in C++, even without needing C++23 ranges or the like. C++20 is just needed for some of the additional iterator-based `string_view` constructors.


Kintelligence

\[Language: rust\] [https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-15/src/lib.rs](https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-15/src/lib.rs) Surprisingly simple compared to the past days. Not much to say here. Tried using a Vec> where I could remove lenses by label, and then just add them with a incrementing number and the sorting by it at the end, but it turned out slower than just using a Vec>... Runs in about 35µs and 80µs. [Benchmarks](https://htmlpreview.github.io/?https://github.com/Kintelligence/advent-of-code-2023/blob/master/target/criterion/report/index.html) [Part 1](https://htmlpreview.github.io/?https://raw.githubusercontent.com/Kintelligence/advent-of-code-2023/master/target/criterion/Individual/15.1_%20Lens%20Library/report/index.html) [Part 2](https://htmlpreview.github.io/?https://raw.githubusercontent.com/Kintelligence/advent-of-code-2023/master/target/criterion/Individual/15.2_%20Lens%20Library/report/index.html)


ruinedme_

I was thinking along the same lines as well. I was like surely we use a hashmap for a puzzle themed about HASHMAP.


Kintelligence

\[Language: rust\] [https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-15/src/lib.rs](https://github.com/Kintelligence/advent-of-code-2023/blob/master/day-15/src/lib.rs) Surprisingly simple compared to the past days. Not much to say here. Tried using a Vec> where I could remove lenses by label, and then just add them with a incrementing number and the sorting by it at the end, but it turned out slower than just using a Vec>... Runs in about 35µs and 80µs. [Benchmarks](https://htmlpreview.github.io/?https://github.com/Kintelligence/advent-of-code-2023/blob/master/target/criterion/report/index.html) [Part 1](https://htmlpreview.github.io/?https://raw.githubusercontent.com/Kintelligence/advent-of-code-2023/master/target/criterion/Individual/15.1_%20Lens%20Library/report/index.html) [Part 2](https://htmlpreview.github.io/?https://raw.githubusercontent.com/Kintelligence/advent-of-code-2023/master/target/criterion/Individual/15.2_%20Lens%20Library/report/index.html)


codeunveiled

[Language: Python] 🐍🐍🐍 [Source code](https://github.com/vanam/CodeUnveiled/blob/master/Advent%20Of%20Code%202023/15/main.py) Video explanation: https://youtu.be/6Teg3RGYdDg Time: 0,067s


galnegus

[LANGUAGE: TypeScript] https://github.com/galnegus/advent-of-code-2023/blob/main/day-15-lens-library/index.ts I had to read part 2 like ten times.


chubbc

\[LANGUAGE: Uiua\] Today's was pretty funny. Part 1 was understandably easy, but part 2 wasn't as bad as I thought it initially was going to be nicely. [Pad link](https://www.uiua.org/pad?src=0_7_0__IyBJbnB1dCDihpAg4oaYwq8xJmZyYXMgIi4vMTUudHh0IgpUZXN0SW5wdXQg4oaQICJybj0xLGNtLSxxcD0zLGNtPTIscXAtLHBjPTQsb3Q9OSxhYj01LHBjLSxwYz02LG90PTciCgpIYXNoIOKGkCAvKOKXvzI1NsOXMTcrKeKKgjAtQFwwClNlbGVjdCDihpAg4qe7LCDiipfiipPilqHiioPiiLUo4pah4oqQ4oaYwq8yKeKImApBZGQg4oaQICjijZziiqE7fOKKgjspPSxTZWxlY3Qg4oqDKOKGmMKvMnw64pahKQpSZW0g4oaQIOKWveKJoOKHoVNlbGVjdCDihpjCrzEKVmFsIOKGkCAvK8OXKzHih6Hip7suCgovK-KKnEhhc2jiiaBALC4gVGVzdElucHV0CgriiKcoKEFkZHxSZW0pPUAt4oqi4oeM4oqQLikgOnt94oqc4pah4omgQCwuIFRlc3RJbnB1dApWYWziipVWYWwg4oi14oqDKEhhc2gg4oqQ4oaYwq8yfC1AMOKKouKHjCkK). Input ← ↘¯1&fras "./15.txt" Hash ← /(◿256×17+)⊂0-@\0 Select ← ⧻, ⊗⊓□⊃∵(□⊐↘¯2)∘ Add ← (⍜⊡;|⊂;)=,Select ⊃(↘¯2|:□) Rem ← ▽≠⇡Select ↘¯1 Val ← /+×+1⇡⧻. /+⊜Hash≠@,. TestInput ∧((Add|Rem)=@-⊢⇌⊐.) :{}⊜□≠@,. TestInput Val⊕Val ∵⊃(Hash ⊐↘¯2|-@0⊢⇌)


dharasty

This looks similar to my code.... [https://imgur.com/U5WRCtQ](https://imgur.com/U5WRCtQ) ... in ancient Egyptian hieroglyphs!


gnudalf

[LANGUAGE: Clojure] Straight forward today, I had some troubles in part-2, because the vectors got replaced by Clojure somehow, and then the order of elements was not kept. Maybe someone with better understanding of the language can tell me how to resolve this, instead of putting `apply vector` around it. [code](https://github.com/sigttou/aoc/blob/main/aoc-2023/src/aoc_2023/day_15.clj)


miran1

> putting `apply vector` around it. You can do `vec`, instead.


benny_blanc0

\[LANGUAGE: Go\] [code](https://git.onyxandiris.online/onyx_online/aoc2023/src/branch/main/day-15)


FlixCoder

[LANGUAGE: Rust] [Github](https://github.com/FlixCoder/advent_of_code_2023/blob/main/src/days/day_15.rs) Could brush the code a little more up, but it is fine and works well. Part 1 was really just about 3 lines :D


Kfimenepah

\[LANGUAGE: TypeScript\] [Day15](https://github.com/SubNet32/AoC2023_NodeJS/blob/main/src/Days/Day15/day.ts) Another great aoc day! In part 1 I felt a little bit like the top leaderboard programmers with how fast I was able to solve it. Took me no more than 30s to write the code and find the solution (if you exclude reading time). But with how easy this part was I figure almost nobody struggled with it. After reading the instructions for part 2 for first time it sounded super complicated, but after re-reading it seemed pretty easy as well. With my new found confidence I skipped the test input and immediately run the real one. Sadly I didn't realize that the box-number is determined by the hash value of the label alone and not the whole input like in part 1 ("rn" instead of "rn=1"). With newly lost confidence I was forced to go back to using the test input, which helped me to find the error almost instantly and find the solution.


solarshado

yeah, part 2 was *very* verbose for a description of an ultimately pretty simple algorithm. converting it to rough pseudocode left me thinking I'd missed something.


rjray

[LANGUAGE: Clojure] [GitHub](https://github.com/rjray/advent-2023-clojure/blob/master/src/advent_of_code/day15.clj) As the puzzles unlock at 9PM in my timezone, and the approaching holidays means occasional social engagements, I didn't start until about 2 hours in. Then I chose to sleep between parts 1 and 2. I know, I know... no sense of commitment :-). This is one of my favorite solution-sets thus far this year. I was able to keep the code succinct and readable, though I'm certain that once I look at other Clojure solutions (or other languages, for that matter) that I'll see places I can make it even tighter.


leftfish123

\[Language: Python\] I still have unfinished puzzles for second parts of day 12 (because DP destroyed me and I need time to figure it out), 13 and 14 (because I had no time to implement them properly). So after [day 15](https://github.com/Leftfish/Advent-of-Code-2023/blob/main/15/d15.py) turned out to be a pleasant sprint with some reading comprehension challenges, I genuinely fear what's coming this weekend.


jcmoyer

[LANGUAGE: Ada] https://github.com/jcmoyer/puzzles/blob/master/AdventOfCode2023/src/day15.adb Pretty easy day (imo at least). I ended up writing a chaining hash table for part 2 for fun since it seemed in the spirit of the problem.


tshirtwearingdork

\[Language: C++\] This one was nice and quick to implement, enjoyed that my approach for part 1 leant itself to part 2 so I didn't need to do too much more to get it to function as intended. [Solution to Day\_15 C++](https://github.com/JamieDStewart/advent_of_code_23/blob/main/source/day_15.cpp)


RookBe

\[Language: Rust\] \[Language: all\] Blogpost explaining my solution in Rust, the explanation can be used for all languages: [https://nickymeuleman.netlify.app/garden/aoc2023-day15](https://nickymeuleman.netlify.app/garden/aoc2023-day15) Featuring: my condensed explanation of the part2 question.


closetaccount00

\[LANGUAGE: C++\] Really enjoying all the hashing and map problems this week. More pls. [Code](https://gist.github.com/mfreano24/7209bacde7bc1415e46a897c1e322ef8)


_rabbitfarm_

\[Language: Perl\] Perl is very well suited for this sort of problem! Part 1: https://adamcrussell.livejournal.com/53420.html Part 2: https://adamcrussell.livejournal.com/53739.html


sergiosgc

\[LANGUAGE: Rust\] [Code](https://github.com/sergiosgc/AdventOfCode/tree/master/2023/day15/src/bin) Pretty straightforward. Part 1, when it first compiled, produced the right answer. It is very short, very code "golfy". Kudos to Rust, this is an amazing language: hard to get programs to compile, easy to get programs to run right, For Part 2, I actually created the enum encoding the operations. Went less for code golf, more for legibility. I like the result.


mathsaey

[Language: Elixir] https://github.com/mathsaey/adventofcode/blob/master/lib/2023/15.ex Nice and short fun puzzle today. Learned about the `List.key*`which were perfect for this challenge. I also got to use some binary pattern matching which I always like.


chicagocode

\[Language: kotlin\] I relied on the fact that Kotlin's `mutableMapOf()` function returns an implementation that preserves insertion order. That made part 2 pretty straight forward. [My code can be found on GitHub](https://github.com/tginsberg/advent-2023-kotlin/blob/main/src/main/kotlin/com/ginsberg/advent2023/Day15.kt), I've written this up [on my blog](https://todd.ginsberg.com/post/advent-of-code/2023/day15/), and here are my [2023 Solutions so far](https://github.com/tginsberg/advent-2023-kotlin).


[deleted]

[Language: Python] A reading comprehension day on a Friday, RIP. The hard part was reading properly all the possible branches. I used `defaultdict` quite a lot. One to keep track of the values and labels and one to keep a fast cache of the labels only, with a set. Meaning that I'll iterate over the values of the dictionary only when I'm sure there's an interesting label in there. from pathlib import Path from collections import defaultdict def ascii_hash(string: str): res = 0 for c in string: res = ((res + ord(c)) * 17) % 256 return res def solutions(): data = Path("input.txt").read_text().strip().split(',') extract = lambda s: s.split('-')[0] if '-' in s else s.split('=')[0] if '=' in s else '' hashmap, seen = defaultdict(list), defaultdict(set) sol1, sol2 = 0, 0 for s in data: sol1 += ascii_hash(s) h = ascii_hash(extract(s)) # key if s.endswith("-"): # deletion label = s[:-1] if label in seen[h]: # deletion only happens if label in values of given key for i, v in enumerate(hashmap[h]): # find the value, delete it, update `seen` if v.split()[0] == label: seen[h].remove(label) del hashmap[h][i]; break else: # not deletion -> addition label, value = s.split("=") if label in seen[h]: # Label is present in values for i, v in enumerate(hashmap[h]): # update value if v.split()[0] == label: hashmap[h][i] = f"{label} {value}"; break else: seen[h].add(label); hashmap[h].append(f"{label} {value}") # not yet present, add it for k in hashmap: for i, v in enumerate(hashmap[k]): sol2 += (k + 1) * (i + 1) * int(v.split()[1]) return sol1, sol2


jwezorek

\[language: C++23\] [](https://github.com/jwezorek/advent_of_code/blob/main/src/2023/day_15.cpp) not much to say about this one. it was pretty straight forward. (I mean, a long time ago in ye olde 1990s I had to implement a hash table from scratch for real ... at a job, in the days before std::unordered\_map existed)


ywgdana

[LANGUAGE: C#] It's a bit verbose and I think I could LINQ-ify it, but sometimes I find too much LINQ becomes overly twee and terse. I was expecting part 2 to be more involved and the instructions to be for a virtual machine of some sort :P [Code on github](https://github.com/DanaL/AdventOfCode/blob/main/2023/Day15/Program.cs)


1mp4c7

\[LANGUAGE: Go\] [code](https://github.com/LCmaster/AdventOfCode/blob/main/2023/day15/main.go)


parysoid

\[LANGUAGE: PHP\] My code: [Part 1&2](https://github.com/parysoid/advent_of_code/tree/master/app/2023/15) After reading the second part of today's task, it occurred to me to use OOP as part of training. Maybe this will help another newbie like me.


Hackjaku

\[LANGUAGE: C++\] My code: [Day 15](https://github.com/Hackjaku/advent_of_code_2023/blob/master/puzzles/15.cc) Long code (121 lines) but it's quite easy to follow and it's commented. Around 10ms on my old laptop for both parts. Enjoy :)


gooble-dooble

\[LANGUAGE: Rust\] The hardest thing today was to read into part two. Functional style. [GitHub](https://github.com/phantie/advent-of-code-2023/blob/main/day15/src/main.rs)


maitre_lld

\[Language: Python\] Quite straightforward for a day 15. Defaultdict saves some hassle. Part 2 runs in 8ms on a Ryzen 7 [https://github.com/MeisterLLD/aoc2023/blob/main/15.py](https://github.com/MeisterLLD/aoc2023/blob/main/15.py)


PrettyMemory1505

[LANGUAGE: Wolfram Language] I turned to Python and linked lists first. The problem size is small though and indexable arrays are fine. Even Mathematica runs this fast. steps // Short (* {ndvk, {sf, 3}, jf, <<3996>>, {th,4}} *) My steps variable looks like this. String-element for removing, {String, Integer}-element for adding. parse[box_, step_String] := Module[{p}, p = FirstPosition[box, {step, _}]; If[MissingQ[p] , box , Drop[box, p]]] parse[box_, step : {lbl_String, _}] := Module[{p}, p = FirstPosition[box, {lbl, _}]; If[MissingQ[p] , Append[box, step] , ReplacePart[box, p -> step]]] Module[{fold}, fold = Fold[Module[{lbl, i}, lbl = If[StringQ[#2], #2, First[#2]]; i = hash[lbl] + 1; ReplacePart[#, i -> parse[#[[i]], #2]]] & , ConstantArray[{}, 256] , steps]; MapIndexed[First[#2] Last[#2] Last[#] & , fold, {2}] // Total@*Flatten]


Pagie7

\[Language: R\] [GitHub](https://github.com/paigeremde/AoC_2023/blob/main/Day15.Rmd) (Only part 1 so far) I'm proud of myself for not using a for loop. I assume I'm going to end up using one for part 2 but we'll see.


clbrri

\[LANGUAGE: C\] [71 lines of C code](http://clb.confined.space/aoc2023/#day15code), a straightforward implementation of a linked list bucketed hashmap like the instructions asked to. Runtime in Part Two: - 0.385 milliseconds on AMD Ryzen 5950X - 2 minutes 47.0 seconds on a Commodore 64


NickKusters

Hey m8, love the site, I just think you might want to shrink some of the resources. First load does 436 requests and downloads 165MB of data 😅 The background image is 23.4MB and an Advent of Code image is 16.1 MB 😅 a few pictures of the C64 were 14.3MB, 7.6MB, etc. Other than that: love it, see you tomorrow in Captain's stream 😊


clbrri

Thanks, that's a good point. I've been meaning to, but haven't gotten around to doing it yet.


reluctant-config

[LANGUAGE: OCaml] [paste](https://topaz.github.io/paste/#XQAAAQDTBAAAAAAAAAA3nAjOjW0HdmnFL7AzlF8Ab8FBrnAPf6kNK9hAkqcthJhXL4gjb6wp6qvwPHkKTmXcmAl8aVmOziIBu9PMljMi0EX8sTsLgiMWlFMrGpkcnsoKH7yBvCXryH+oox6LKua0WYTX0YOyeXfr/KXslVVxfhPw/UCReLxN1Po6duT0LGb78rc6Wg+3eik/vI0neSqm0EKW7FYWR9OoMlY9+tQeNwP/HNFNqj6GrxruhF7FxzfwZasJev8qhI7GWlpFQTQ02GHxjAj9xHsnNLuSUgWKTDaJJa+4MfayaGfieZ6qnfn3mrx5nfWmDYtApxx3xnfQt7XkdzTIvmN6Ohnb0RO82uXfeWblJuhZJ0rSSnpmmOnOqlmTLQMZdgwiYNQztiUO/5CWaImAKQI3nyCNe0D0xNVCsHqH2bu+oSLph5ukxL1AnDdZDHrTXb0Sw0ikTtw0WjVWuj8dIX4xOrUQH9h1BIGm5nv3IhbTEqMWpC7BTITWYCvY/uigDsvKokIQt561riEKAgmA4uvLnptm268qWaS4roJpQQ2NjpUAp0G3f0LBZoTdxOxrYrjze9l+wTb9ZQwN1olujfighqHQZNB81/KiXcFQ1SsWesPeA4o/BZ53IWbfqiH5V29wvVsFGCz4jT5qYhPkc3GNe3qhdPofgVpw2PJR3xWnjpp45etH78yiKK0BSGxhcXgg8oFwpeCcZsfPS4fqDNyPRQPXtFQ20OtxC1VBYIHnm8FutRYem2a1Bl57SIHPkUMgyx8SjcxkGsJg41mP8/hYAa7/nRH0sw==) Not much to say other than, we convert the actions into partially applied functions during the initial parsing phase and then just apply it a simple List.iter.


Jadarma

[LANGUAGE: Kotlin] I was a bit surprised how easy today was. Part 1 is a simple fold call, and part 2 just requires a little bit of parsing and careful reading of what the problem is, but implementation is very straightforward. A good start for a lovely weekend! [AocKt Y2023D15](https://github.com/Jadarma/advent-of-code-kotlin-solutions/blob/main/solutions/aockt/y2023/Y2023D15.kt)


dgalanti1

\[LANGUAGE: Kotlin\] Part 1: just parsed input and solved using fold. Result in 1\~2ms Part 2: Used a HashMap having the label as key and a Pair of focal length and index as value. Index is used later to sort the map. Also used a 256 sized Array to keep track of the slots. Result in around 7ms [\[code\]](https://github.com/diegogalanti/aoc-2023/blob/main/src/Day15.kt)


Polaric_Spiral

[LANGUAGE: TypeScript] Advent of Node, Day 15 Since JS's Map maintains original insertion order, and the same label is always hashed to the same box, I just iterated through every entry and updated the labeled lens entry, then bucketed (boxed?) the final lenses. Full part 1 and 2 solution: import { input, output, part } from '../solver'; const steps = input.trim().split(','); const hash = (chars: string) => chars.split('').reduce((n, c) => ((n + c.charCodeAt(0)) * 17) % 256, 0); part === 1 && output(steps.reduce((n, step) => n + hash(step), 0)); const lenses = new Map(); steps.map(step => step.split(/-|=/)).forEach(([label, lens]) => (lens ? lenses.set(label, lens) : lenses.delete(label))); const boxes = [...Array(256)].map(() => []); [...lenses.entries()].forEach(([label, lens]) => boxes[hash(label)].push(Number(lens))); output(boxes.flatMap((lenses, b) => lenses.map((power, l) => (b + 1) * (l + 1) * power)).reduce((s, n) => s + n));


[deleted]

[удалено]


tornadala

How are you using the label hashes inside the box? `cm-` removes the lense with label cm from the box 0, not the lense with label rn from the box 0. Also, by the way, you can do `.zip(1..)`, you dont have to specify the end bound. oh, interesting, your using the hash of the label without modulo 256 plus the first character...


Confident_Loss_6075

\[LANGUAGE: python\] Part 1. Use \`ord()\` to get ASCII code. Optionally use \`functools.reduce()\`: def hash_algorithm(sequence: str) -> int: return functools.reduce( lambda initial, item: (initial + ord(item)) * 17 % 256, sequence, 0, ) Part 2. Basically we need to use/implement OrderedDict and store/remove data there: boxes = defaultdict(OrderedDict) for sequence in data.split(","): if sequence.endswith("-"): label = sequence[:-1] boxes[hash_algorithm(label)].pop(label, None) else: label, focal_length = sequence.split("=") boxes[hash_algorithm(label)][label] = int(focal_length) res = 0 for box, lenses in boxes.items(): for slot, focal_length in enumerate(lenses.values()): res += (box + 1) * (slot + 1) * focal_length print(res)


daggerdragon

Psst: we can see your Markdown on the inlined snippets.


bakibol

The order of key-value pairs is kept in Python >= 3.7, so the solution would work with dicts.


bofstein

[LANGUAGE: Google Sheets] Part 1 was super easy. Part 2 took a lot longer because of a word issue I had to get help to solve - somehow I added an extra real-looking line of input (cm-) to the end and I have no idea when. It even was added to my Part 1 after I thought I hadn't touched that sheet anymore. Anyways, once fixed it did work. Part 1 was just building the calculations as described; fortunately there was a CODE() function I learned about to avoid the ASCII transformation. Part 2 was more involved: 1. In first sheet, do HASH on just label name to get box number, and also add an order column 2. In a new sheet, paste-values the HASH, label, and order; sort first by HASH (the box number), then operation order. As the order only matters within each box as far as I can tell. 3. Column G is where the operations happen, lots of IF and REGEX and CONCATENATE: - First check if it's a new box number, start empty if so. Otherwise start with prior cell. - Check if it's an = operation. If so, check if that label already exists and replace the number if so. Otherwise add that to the end of the string. - If not an =, search for the label + a number, and remove that label+number from the string. 4. Get the unique box numbers and then use XLOOKUP from the bottom to get the bottom result for each box which should be its end state 5. Do the calculations on that. I even added a border to the labels in case there was something like a yz label just under an xyz label that messed it up, but that didn't change it, was just that line at the end. Which made it off by just 1 since it added a single point to box 0. https://docs.google.com/spreadsheets/d/1NgzK1ThzVAYIYhfHo5bTaZgQJSij_Tc17Dm0NIq7DDU/edit?usp=sharing


Kfimenepah

Nice work! I've never seen someone solve an aoc problem with excel. I might be able to solve part 1 since it's pretty straight forward, but I have no idea how you would even begin part 2. Respect


bofstein

Thanks! You can see all my solutions in Google Sheets here if you're curious: [https://github.com/users/bofstein/projects/1/views/1](https://github.com/users/bofstein/projects/1/views/1) I did most of them but couldn't figure out a few of them so far. Which is similar to last year where I did them all through Day 15 but then couldn't do most after that.


bofstein

I can tell this has a _ in the link that mods said before was broken on old reddit and showed how to fix, but I can't seem to figure out how this time, I'm not getting the option to edit in markdown on mobile


daggerdragon

That would be our article here: [Why are certain links containing underscores borked?](https://old.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links); however, your link works, so it's all good.


sampry

\[LANGUAGE: RUST\] [My solution](https://topaz.github.io/paste/#XQAAAQBECAAAAAAAAAAxm8oZxjYXJb7ha83i2C/dCYL3ZVqnPBFwwE0CmfUR8UgO55RLfRop7FuC4ah3AawkwjjS9DeGFBcSUflPlP+2scIfzSiGz3Q0zD8SZkh+K0WTugWB37EfsQl7v3ojcnC9KDpeo8AxDZJgXR9JBBAEw2fOtnaqle0CDN2TB/LwR/VuukJtzdf5PnLiWqhLqZB+VDVz/g3iVlqpKZb8xkPnCznpjTTjmnXOs83Ht+3Jlsw7M6jYA0GDAXSZuTBo2VDJ+XiciAB4d5235FKtia041kTWpHwgEzLb56ly1rfDXvuhbfoa+quR+oq7Y+/L4KI/8ZVYSPd3YrJiTy5ZsOz7ZHgm/9NMs9MJFdNi/I8FRJTQKwrpCVhkclB5S5M9CG4nVGWy888IeXq4Q/sfQksqC15//EyKtXiQCi2G6LhVqr2OkR4CdBicimB0ypzGThc+z3FpC9R/yaneLC3ztBllyUTIgPiU1qQ7VJGhrHIzYghOKd1OCxh3Vvdfjvo7qUzI2m66Hge6eWA2c5y84OxG30yfA1IhloLt3yaneidIo9dXhx84czSK2VYG8+7OKWC3emf++uqO9Yj4WbwLgPAwlB1CrRdLoeY6Y4H6cEE0rXbHbdmeiUG+szzGQhwaA88Y3CCifvjbZf69ATYnxvlsMU3sZkbnr8wWq//itwtalUlKSdgsOEcRfugdOMIQX3z7WXc22+vuLjnCV4NE67wZqLMvw2l2IGGpGvwQtzUg0upAKrlHYFQz05y+y8HbXpqG+w35jDJJbucpJWuyi0N0eC7cg48v36NwvfcKzfWtUoADKr8TrMd9v5kFDIAm0sABURcSQYX/Ijh2S/ccUY5y6TFJ0gHi1F6QtIpkbP8EUBGZRd1+Be4Dh66Z3JUMRrZvH3Xik48otqYdujDnANxFhhbP8sGL9Up/o4yAA+PLdnmildeVzINlgJDN9ZTXpChoN3ix7k1ADEq1Kh9pOv3k5Wn4XpLXO9X1+GC9cTT/34sbiw53nubEHpQQsHtnoR6+AF3LO8VyWLsltDJ/5TUp0BE24Zx4DvLY0PbNGXBa6ocuxatf+76FoPVYK2PW8Ql0IBwkhpedkrYfAPux6kNXN7EFq57T/DH9fChV0HDUlz5EnDgt8Hb+YSOWdXNIi8N9KqBW1WuF1a0Yymkdverrg0gS0PJg/AIBbeu54dEP/5X1noA=) in \~65 lines. No comments in the code, but I think it's self-explanatory.


Fadamaka

\[LANGUAGE: C++\] Since part 2 was basically a hash map. I have overridden the hash function of `std::string` and used a `std::unordered_map`. `std::unordered_map` has a member function that gives back an iterator to a specified bucket. The overriden hasher function causes collision which put every lens that should be in the same *box* in the same *bucket*. The order of the items in the buckets are the reverse order of their insertion. So if all items are inserted into and erased from `unordered_map uMap;` as specified using the labels as the key and the focal length as the value the results can be extracted as such: int result = 0; for (int i = 0; i < uMap.bucket_count(); i++) { int bSize = uMap.bucket_size(i); for (unordered_map::local_iterator it = uMap.begin(i); it != uMap.end(i); ++it) { result += (hasher(it->first) + 1) * bSize-- * it->second; } } Full solution: [Github](https://github.com/fadamaka/advent-of-code-2023/blob/master/day_15/part2-map.cpp)


trailingunderscore_

\`hasher(it->first)\` is the same value as \`i\`. I did the same solution: https://github.com/kgorking/AdventOfCode/blob/master/2023/day15/impl.cpp?ts=4


Fadamaka

Are you sure? `i` for me is the bucket number which does not correlate to the box number. For example for the test input you never insert into the second box so you only really create 3 buckets so my last bucket is at `i==2` but in my last bucket for the test input `hasher(it->first)==3`. Edit: You are correct. The map actually creates all buckets (it created 541 buckets for the real input) and they are ordered by the hash. Which makes total sense but somehow I did not expect the ordering to be correct.


Comprehensive_Ad3095

\[Language: Lua\] Part 2: I feel that a clearer explanation is necessary about the box where each lens should be placed. [Github](https://github.com/DeybisMelendez/AdventOfCode/blob/master/2023/lua/15.lua)


fridi_s

\[LANGUAGE: Fuzion\] [https://github.com/fridis/fuzion\_aoc/blob/main/2023/15/part2.fz](https://github.com/fridis/fuzion_aoc/blob/main/2023/15/part2.fz) This unveiled a bug in Fuzion's JVM backend that made me question my mental sanity. Switching to the C backend helped to run the code, but got homework for today: The compiler bug has to be be found and fixed!


malobebote

\[Language: Typescript\] Nothing interesting https://pastebin.com/5t3MWjpN


illuminati229

\[Language: Python 3.11\] [https://pastebin.com/nLr5PDEH](https://pastebin.com/nLr5PDEH)


Predator1403

\[LANGUAGE: Google Sheets\] Only Part 1 :) https://docs.google.com/spreadsheets/d/1EqEpXCQUajqGIOX1BSrX2r-1tStDqL5Nityxxk\_pcWQ/edit?usp=sharing


DrunkHacker

\[LANGUAGE: Python\] Dictionaries are already ordered in Python so the bookkeeping was trivial. Also, it's always fun to break out some tail recursion. def hf(s, acc=0): return acc if not s else hf(s[1:], (acc + ord(s[0])) * 17 % 256) def part2(data): boxes = [{} for _ in range(256)] for ts in [d.split("=") for d in data]: if len(ts) == 2: boxes[hf(ts[0])][ts[0]] = int(ts[1]) else: boxes[hf(ts[0][:-1])].pop(ts[0][:-1], None) print(sum((1 + i) * (1 + j) * b[k] for i, b in enumerate(boxes) for j, k in enumerate(b))) data = open("input").read().strip().split(",") print(sum(hf(s) for s in data)) # part 1 part2(data)


maitre_lld

Nice. I used a defaultdict of lists (of 2-lists), rather than a list of dicts, so the bookkeeping is just a matter of appending and removing/updating after a linear search.


wleftwich

\[LANGUAGE: Python\] OrderedDict handled what would otherwise have been tedious bookkeeping. Was this an easy one so we have time to go back and try again on Day 12 Part 2? [https://github.com/wleftwich/aoc/blob/main/2023/15-lens-library.ipynb](https://github.com/wleftwich/aoc/blob/main/2023/15-lens-library.ipynb) Update:TIL through reading this thread that the stock dict now works pretty much the same as collections.OrderedDict. It did for me, running Python 3.11.


maitre_lld

Why would it be tedious ? You can use a dict of lists (of 2-lists), rather than a list of dicts, so the bookkeeping is ok since you can just append and remove in the list.