r/adventofcode • u/daggerdragon • Dec 10 '21
SOLUTION MEGATHREAD -🎄- 2021 Day 10 Solutions -🎄-
--- Day 10: Syntax Scoring ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - Format your code properly! How do I format code?
- The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:08:06, megathread unlocked!
65
Upvotes
12
u/bp_ Dec 10 '21 edited Dec 11 '21
Perl ($_% category)
Readability notes for those less versed in Perl:
in the
for (@lines)block, all of the free-floating regular expression matching/[<][}]/and substitutings/[<][>]//is implicitly done on the loop element, the global$_variable.for my $line (@lines) { my $done; until ($done) { $done = 1; $line =~ s/[(][)]// and $done = 0; ...; } }I don't generate the autocompletion, because I'm just left with either syntax errors or open, unmatched parens; for part 2 I just go through that list of parens backwards to count my points.
<}[)is worth 1,197 points, not 3). Works With My Input(TM) 🤷for @lettersline, where$_instead holds each element in the@lettersarray.In a similar vein,
1 while ...evaluates the expression1(i.e. it does nothing) while the condition is still true (in this case, whether replacements were done last time around).1 while, run.sort {$a <=> $b}) Perl helpfully sorts them alphabetically (1 10 100 2 20 3) :(@scores/2) Perl evaluates the expression as its number of elementsqw- ( 1 [ 2 { 3 < 4 -is the lazy man's way of writing( '(' => 1, '[' => 2, '{' => 3, '<' => 4). The "quote words" "operator" usually writtenqw()orqw[]or evenqw<>but obviously that would've gotten in the way today, and it works with any symbol e.g.qw--orqw??or evenqw aa10
u/GaloisGirl2 Dec 10 '21 edited Dec 11 '21
COBOL
9
u/CCC_037 Dec 10 '21
Rockstar
Part 1:
Part 2:
4
u/gottfired Dec 10 '21
Github Copilot
Today was pretty easy for copilot again.
E.g. part 2 could be solved like this
Full solution is here:
https://github.com/gottfired/advent-of-code-2021-copilot-edition/blob/master/day10.ts
4
u/hugobuddel Dec 11 '21 edited Dec 11 '21
Rockstar, Part 1 (works in Rocky and in Santriani now)
This is not a conventional genre for rockstar developers to chose, but it works really well for this problem. I'm unreasonably happy with how it turned out.
The
confessionfunction essentially pops the last element, when a closing bracket is found. Apparently Rockstar only has a build-in for popping the first element. It came out quite nicely.3
u/[deleted] Dec 10 '21 edited Dec 10 '21
Python 3
Part 1:
Part 2:
3
u/voidhawk42 Dec 10 '21
I'd like to post my APL code, but I don't have a good array-based way to do this yet - my code is too ugly to share. :)
So here's my solution in Clojure, which I think is pretty nice - single reduction to get the data for both parts.
2
u/diplodicus_ Dec 10 '21 edited Dec 10 '21
Golang 2943/1670 - sat down to do it a few minutes late, and Go isn't a fast language, but pretty happy with this!
Here's my part 2: paste
2
u/Extension_Wheel_2032 Dec 10 '21 edited Dec 10 '21
Clojure, with instaparse. Kinda messy, could be cleaned up for sure, and the parser is probably unnecessary.
paste
2
u/iamnguele Dec 10 '21 edited Dec 12 '21
Java
2
u/Spock_42 Dec 10 '21 edited Dec 10 '21
This is my Ruby solution to Part 2. Part 1 is similar, just a different scoring pattern. Just learning Ruby for the first time via AoC, so any C&C is appreciated.
2
u/codefrommars Dec 10 '21
C++
Straightforward with a stack. Special char to make code simpler avoiding empty stack checks.
2
u/cylab Dec 10 '21 edited Dec 10 '21
Kotlin: https://github.com/cylab/advent-of-code-2021/tree/main/src/test/kotlin/day10
The first time the solution was wrong for part2 due to using Int instead of Long :((
2
u/TPlantB Dec 10 '21
Lua
Pure Lua and I could reuse the stack from yesterday.
gotois cool, right?2
u/_mattmc3_ Dec 10 '21 edited Dec 11 '21
Fish shell solution
This one was a pretty easy array stack implementation
2
u/Calkky Dec 10 '21 edited Dec 10 '21
Groovy
(link for old.reddit users)
2
u/xelf Dec 10 '21 edited Dec 10 '21
Python, with a little regex and help from lstrip
Had to do my original version using a cell phone, was not fun.
Here's a cleaned up version I did when I got access to my computer.
There's a massive trick you can do; removing the pairs from the input file
This makes the subsequent parts a lot easier by just building up the 2 line lists you need for each part.
shenanigans:
part1:
part2:
Also pretty happy with the
line.lstrip('{[<(')part. That was a bonus free win.2
u/0x5ubt13 Dec 10 '21 edited Dec 10 '21
My solution in Python :)
Edit: Paste
2
u/Biggergig Dec 10 '21 edited Dec 11 '21
PYTHON
C++
21
u/george_v_reilly Dec 10 '21
Python 3. I used the little-known for-else construct in Part 2 to discard the corrupt lines.
14
u/Smylers Dec 10 '21 edited Dec 10 '21
Today's Vim keystrokes solution is actually pretty elegant, solving both parts together. At least, the algorithm is elegant. The syntax is a complete mess, with all those brackets, backslashes, and forward slashes:
That should leave you with two lines, error score on the first, middle completion score on the second.
Right now I've got to get some children some breakfast. I'll update later with an explanation.Update — here's what it's doing. First remove all matching pairs, from the inside out:
With the sample input, the first line:
would turn into something like this:
except without the spaces, which I've added to make it clearer to see where each of the still-there brackets came from. Squashing those out shows we still have some matching pairs:
That's because only empty matching pairs were removed. Doing that emptied out some other matching pairs. Those haven't been removed, because, even with the
/gmodifier,:s///only matches against text that was in the initial string, not text resulting from its own actions.So to remove all matching pairs, do that again.
g&repeats the most recent:%s///command. How many times do we need to do that? Until it fails. Theqaline is the loop infrastructure from Day 1, defining@aas doingg&until it can'tg&no more.At this point, with all matching brackets removed, any line which still contains any closing bracket is corrupt. Let's replace a closing bracket with its points (preceded by a
+):In the sample input, the 3rd line, which looks like this without its matching pairs:
gets turned into:
Of that we only want the score of the first non-matching bracket on a line, so delete everything else:
The sample input now looks like this:
For the error score we want to add all those numbers which are currently scattered among the incomplete lines, so move any line with a
+in it to the top of the file:The next line of keystrokes finds the last
+in the buffer, joins from there to the first line (so all the+-separated numbers are on a single row), and sums them with@sto yield the error score.@s, a re-usable macro for evaluating the current line, was defined yesterday.The remaining lines are the incomplete ones. Replace every bracket by the points of the missing pair that would complete it:
The first line of the sample input now looks like this:
Missing brackets are scored from right to left, so the above wants turning into:
(ironically adding a confusing number of brackets, just when we'd got rid of them all). To start with, get rid of the
+at the very start of a line, because it's about to get in the way. The previous substitution left us on the first character of the bottom line, so⟨Ctrl+V⟩there starts a block,{extends it to the first line,jmoves that down to the second line (because the first line has our part-1 answer on it), andddeletes all those pluses.Then we can add the outermost set of brackets with:
That gives us:
We want to repeat that substitution for each of the other
+s in the line: a+followed by one of1–4(but not, crucially, a5) needs everything after the+bracketing and multiplying by 5. How many times do we want to repeat that? Until it fails. So that's just@aagain, as defined above. Code reuse!(It's a different substitution that's being repeated this time: the
g&in the macro repeats the most recent:s///at the time of invoking it, not the one that was around when it was recorded.)Technically the closing brackets end up being added in exactly the wrong order, but because they're all parens, that doesn't matter:
)))))))works just the same as))))))), even if one of them is backwards.The initial
+s were removed to avoid the outer expression being caught up by the regexp and wrongly multiplied by 5.Now we have all the individual completion scores on line 2 onwards, so sort them:
Then find the median. Because of the error score on line 1,
50%actually jumps to the line before the median. This turns out to be useful, becaused2Gdeletes from there to the lowest score, on line 2. That leaves the cursor on the median, but with the other half of unwanted scores on the row below it.jdGtakes care of those, and you're left with your 2 answers.See, told you it was elegant! Thank you to anybody who read this far. And do try it out — much of today's keystrokes are those
:commands, which are copy-and-pasteable.13
u/SuperSmurfen Dec 10 '21 edited Dec 10 '21
Rust (740/409)
Link to full solution
What a day! First day this year I got top 1k on both parts! I just iterate over the chars and keep a stack over the unmatched opening braces. If I see any of
([{<I push it on the stack and if I see any of)]}>I pop off the stack. If the thing at the top of the stack does not match the closing brace then the line is invalid. This fits nicely in a single match statement:The same strategy also makes part 2 really easy. The stack, after you have iterated over all the chars, contains the information about which braces we need to add. So just iterate over the stack and compute the score:
Finishes in about
250μson my machine.12
u/JustinHuPrime Dec 10 '21
x86_64 assembly
Part 1 and part 2 were both structurally similar, involving a stack. The main difference was how I handled newlines.
I needed to write a sorting function back during day 7, so I got to re-use that during part 2.
10
u/alchzh Dec 10 '21 edited Dec 10 '21
Python
Got a nasty cut on my right index finger so typing is a pain, no fear, advent must go on!
10
u/Mats56 Dec 10 '21 edited Dec 10 '21
Kotlin, not stack or recursive
Main part is stupid, but it worked. Just removes pairs again and again until nothing changes. So
(<{}>becomes(<>which becomes(.Then for part 1 just find the first occurence of a closing bracket in the remaining string. For part2 just flip the remaining string and replace each with the matching closing bracket.
Tried to make it fully functional without any mutations. The generate infinite sequence, zip + takewhile they are different worked nice.
Full here: Day10 Kotlin
8
u/jonathan_paulson Dec 10 '21
Python. 375/129 :( Video of me solving.
8
u/4HbQ Dec 10 '21 edited Dec 12 '21
Python, using a stack for index numbers (negative for open, positive for close) for easy matching and scoring.
Edit: the "clever trick" is in
<{[( )]}>'.find(p) - 4. Here, find gets the index of character p in the string<{[( )]}>. For example,<has index 0 and>has index 8. Now if we subtract 4,<gets -4 and>gets +4.When the parsing hits a negative number (let's say -4), we put its opposite (+4) on the stack and wait for it's match.
7
u/daniel-sd Dec 10 '21
Python
Plain and simple stack.
Part 1 - 16 lines
Part 2 - 24 lines
See the initial commit for the sloppiness that managed ranks 402 and 262 :P
7
u/sefujuki Dec 10 '21 edited Dec 10 '21
C spoiler
Nope!!! The result of the subtraction is converted to
intwhich loses precision!7
u/pimpbot9000k Dec 10 '21 edited Dec 10 '21
Python 3.My createst algorithmic achievement so far in AoC:
My greatest brainfart today was that if I reverse a string
I get
7
u/MCSpiderFe Dec 10 '21
CSpydr
(CSpydr is my own programming language written in pure C)
All my AoC 2021 solutions in CSpydr: GitHub repo
Part 1:
Part 2:
6
u/bluepichu Dec 10 '21
TypeScript, 8/22. Code here.
A little disappointed that I obo'd the scores for part 2 on my first attempt since I could've gotten 8/6 or 8/5, but this narrowly improved my record for best day this year so I'll take what I can get.
6
u/janiczek Dec 10 '21
APL
The underlying idea is
r: you remove substrings()etc. from the input until the "weird stuff" remains.Then, if there are only opening parens, it's incomplete. In the other case it's corrupted.
6
u/BaaBaaPinkSheep Dec 10 '21
Python 3
Finally, I can make use of the for else loop. Pretty straight forward using a stack.
https://github.com/SnoozeySleepy/AdventofCode/blob/main/day10.py
5
u/leijurv Dec 10 '21 edited Dec 10 '21
Python, 64th place, 35th place
Screen recording https://youtu.be/1HVImCuOe6g
Part 1
Part 2
5
u/[deleted] Dec 10 '21
Haskell
Today was easy, though it didn't prevent me from getting stuck on silly bugs :P
I think the list comprehension to filter for subtypes is a bit ugly but I couldn't find an alternative way to do it.
5
u/q3w3e3_ Dec 10 '21
google sheets
5
u/RealFenlair Dec 10 '21
Python3
5
u/williamlp Dec 10 '21 edited Dec 10 '21
PostgreSQL
Not so bad with the trick of iteratively reducing matched pairs [] () {} <> until none are left.
For part 2 it's interesting that after you do this what is left is a base-5 representation of the score.
5
u/Tipa16384 Dec 10 '21
Python 3
Stackless solution that uses base 5 numbers.
5
u/mockle2 Dec 10 '21 edited Dec 10 '21
python, both parts, stackless. I initially used a stack but for fun I've also made stackless version. It takes about twice as long as the version with a stack
5
u/hugseverycat Dec 10 '21
Python with comments
Since any closing bracket must pair with the most recent opening bracket, for today’s puzzle I just kept a list of all the opening brackets. When a closing bracket is found, remove the most recent opening bracket from the list and see if it pairs with the closing bracket. If not, the line is corrupted.
Which works out nicely for part 2, since the only brackets remaining in the list are unpaired opening brackets. So just go through them (starting with the most recent) and get your score. The most trouble I had with this is that I repeatedly misread how the scores were calculated in Part 2.
https://github.com/hugseverycat/AOC2021/blob/master/day10.py
5
u/AvshalomHeironymous Dec 10 '21 edited Dec 10 '21
Prolog
My next_token predicate is a little more elaborate than needed because I didn't know where part 2 was going to go. I ended up just having to add the fourth parameter (I had even made the next_token(C,[],...) case for part 1 it just didn't have a score associated with it).
5
u/chicagocode Dec 10 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
I used to ask a much more simplified version of this in programming interviews, back when I used to ask people to code (I don't any more, we just talk). My solution for both parts uses a sealed class structure. Before today, I hadn't even seen
filterIsInstance<T>. It's nice because it returns a typed list for you instead of just filtering.5
u/vbe-elvis Dec 10 '21 edited Dec 10 '21
Kotlin, Not really a problem this round. Did put in the wrong answer first by calculating with Int instead of Long
5
u/narrow_assignment Dec 10 '21
AWK
Part 2 using the quickselect algorithm
5
u/oddrationale Dec 10 '21
Here's my solution in F# with Jupyter Notebook. Used a recursive solution with a List as a stack.
4
u/Mathgeek007 Dec 10 '21
Excel - 457/2489
VIDEO OF SOLVE
Part 1, I successively removed (), [], {}, <> from each string, until there were none. THen checked if there were any leftover close brackets. If there were, reject and calculate from the first one. For Part 2, if that row didn't score in Part 1, from last to first, check which opening brackets are left, and iteratively score. Not too shabby today. Had a few small missteps, but it worked overall!
4
u/autid Dec 10 '21
FORTRAN
Why does it gotta be medians. :(
4
u/nocstra Dec 10 '21
Haskell
4
u/Laugarhraun Dec 10 '21
Common Lisp
https://github.com/brunal/advent-of-code-2021/blob/main/10.lisp
4
u/u794575248 Dec 10 '21
J Language (an array programming language based primarily on APL)
4
u/zniperr Dec 10 '21
python3:
4
u/kwenti Dec 10 '21
Python
My solution in Python, using a stack to keep track of my needs for closure.
Cheers,
Quentin
4
u/timvisee Dec 10 '21 edited Dec 10 '21
Rust Very concise.
Part 1 0.011ms (11μs)
Part 2 0.015ms (15μs)
day01 to day10 total: 0.819ms (819μs)
4
u/allaboutthatmace1789 Dec 10 '21
Clojure
Blog
Source
4
u/[deleted] Dec 10 '21
Python
using stacks
4
u/Edicara237 Dec 10 '21
Solution in Clojure: https://curls.it/cp4Ra
Nothing fancy. The function that analyses a single line returns either the first illegal character or the stack of non closed brackets and thus can be used to solve both part 1 and part 2.
4
u/semicolonator Dec 10 '21
Python, 26 lines
Using a parser for part 1: See here
4
u/Nerdlinger Dec 10 '21
Swift:
Yep. Boring straightforward stack usage. Why settle for anything more?
4
u/TiagoPaolini Dec 10 '21
Python 3
I used a stack (last in, first out) to keep track of the open segments, then I compared if the closing marker matched the openings on the stack (in the order from last to first).
4
u/__Abigail__ Dec 10 '21
Perl
Finding the incorrect closing parenthesis with a single regexp:
If
/$pattern/xmatches, then the line is corrupted, and$2contains the offending paren.4
u/clumsveed Dec 10 '21
Java Solution
Day 10 Solution
All Solutions: repl.it
I reworked my original "if"-riddled code to utilize maps. Although, I still don't love it. I wanted to use a Class or a record to organize my symbols/values, but it still seemed loopy and iffy, so I'm sticking with the maps.
Now, let's go check out people's regex solutions so I can hate myself. haha
4
u/mc_ Dec 10 '21
Erlang solution. Erlang's prepend operation for lists makes implementing a stack trivial for this.
4
u/skarlso Dec 10 '21
Go / Golang
Tutorial explaining how and why to use a stack
4
u/tubero__ Dec 10 '21 edited Dec 11 '21
Rust solution with a focus on conciseness. (In real code I would use match instead of the hashmaps, but that makes the code a lot longer)
1
u/RJdaMoD Dec 10 '21 edited Dec 10 '21
Mathematica
Both parts in one:
1
u/Imnimo Dec 10 '21 edited Dec 10 '21
Python, 606/372
Did you guys know that while ( and ) are adjacent in ascii, the other three pairs have an intervening symbol?
https://pastebin.com/JU1aq68B
1
u/mine248 Dec 10 '21 edited Dec 10 '21
Python 3.9
1
u/Snoo_41044 Dec 10 '21 edited Dec 10 '21
Python
Part 1
Using a stack and dictionary to find the first error and increase the error score by the points for each syntax breaking bracket.
Part 2
Stack solution as well but create a list of
1
u/Early_Adeptness_2814 Dec 10 '21
cpp part2
1
u/Illustrious_Fortune7 Dec 10 '21 edited Dec 10 '21
In Kotlin
https://github.com/ritesh-singh/aoc-2021-in-kotlin/commit/e0852dedd75dd794c1046ae1a87ec05a1009ae2e
1
u/guytv2017 Dec 10 '21 edited Dec 10 '21
KOTLIN
Code is here
1
u/Diarmuid_ Dec 10 '21
Python and regexps
1
u/[deleted] Dec 10 '21
Python
nothing special really. this is one of those problems, where you are glad its an easy one if you have done something like this already, but if you havent you want to curse it forver
1
u/raxomukus Dec 10 '21
Python
Clean and readable. Proud of my solution today
1
u/pistacchio Dec 10 '21 edited Dec 11 '21
Typescript:
1
u/[deleted] Dec 10 '21 edited Dec 10 '21
Rust
Stack based solution.
Code
1
u/BuildingDumbShit Dec 10 '21 edited Dec 10 '21
I always do Advent in PowerShell but never usually post to Reddit. Enjoy.
PowerShell
5.1.19041.1320
Paste
1
u/[deleted] Dec 10 '21 edited Dec 10 '21
1
u/vishalthakur99 Dec 10 '21
Java Solution
Sorry if its a bit newb
1
u/CptFisk Dec 10 '21 edited Dec 13 '21
C++
No expert but think it looks decent
1
u/JackyReacher Dec 10 '21 edited Dec 10 '21
TypeScript / Deno
paste
1
u/Life-Engine-6726 Dec 10 '21
CPP
first 2-digit day, a bit different than `brainfuck`-ish problems from past years
ungolfed
it would've been painful++ without this line : `...stop at the first incorrect closing character on each corrupted line`
1
u/Drjakeadelic Dec 10 '21 edited Dec 10 '21
Python. A lot of Enums and recursion ;).
1
u/SV-97 Dec 10 '21
It seems like my solution (Python: https://github.com/SV-97/AdventOfCode2021/blob/main/Day_10_2/main.py) differs a bit from the usual stack based approach here (which I used at first for calculating the scores in part 1): it essentially revolves around finding the fixed point of a certain regex substitution. I apply a regex substitution to remove all open-close pairs repeadetly until I arrive at some fixed point of the subsitution. Lines in this fixed point will either consist solely of opening parens/braces etc. or contain some closing ones. If they contain closing ones they're invalid and the leftmost closing one is the first one which makes the string invalid. Just get the value for that and sum.
For part 2 we take all the strings of just opening ones of, map the symbols to the right digits, interpret the result of each line as a vector and take the dot-product with powers of five. Then just take the median of the result and you're done.
1
u/bmatcuk Dec 10 '21 edited Dec 11 '21
Julia
Fairly straight forward, part 2 below. Just used a stack to keep track of the closing characters that I'm expecting to see. At the end of the line, score the remaining characters in the stack.
1
u/theophilusbones Dec 10 '21 edited Dec 10 '21
Python
Both parts in one loop; nothing fancy here today, I found yesterday much more fun!
https://github.com/harry-gibson/advent-of-code-2021/blob/main/day_10/day_10.py
1
u/EnisBerk Dec 10 '21 edited Dec 10 '21
Python 3
https://github.com/EnisBerk/adventofcode/blob/master/day10/tools.py
1
u/garciparedes Dec 10 '21 edited Dec 10 '21
Here is my 🦀 Rust solution for the 🎄 AdventOfCode's Day 10: Syntax Scoring:
1
u/egel-lang Dec 10 '21 edited Dec 10 '21
EGEL
1
u/itistheblurstoftimes Dec 10 '21
emacs lisp
1
u/Bergdublone Dec 10 '21 edited Dec 10 '21
My C# Solution:
using System.Collections.Generic;
namespace _2021_10 { public class Program { static void Main(string[] args) { Console.WriteLine("Teil 1: Beispiel Lösung ist: {0}\r\n" + "Teil 2: Beispiel Lösung ist: {1}", Part1_2("Example.txt", out UInt64 solution2), solution2);
}
1
u/LuckyLactose Dec 10 '21 edited Dec 10 '21
SWIFT
Nothing fancy in this one, I think.
Full repo here.
Cut down version here, some obvious stuff omitted for brevity:
1
u/Zealousideal-Pen9091 Dec 10 '21 edited Dec 15 '21
Here is a simple Python solution:
3
u/e36freak92 Dec 10 '21
AWK
3
u/sim642 Dec 10 '21
My Scala solution.
Debated in my head whether to write a recursive decent parser from scratch or try to hack it together with Scala parser combinators and decided to try the latter. I definitely abused the latter...
In part 1, I needed to distinguish incomplete and corrupted lines, but both give parsing errors. I decided to just regex the parsing error message to know whether it was because of an end of line (so incomplete) or some other expected character (corrupted).
In part 2, I thought I was doomed with the combinators, but then came up with an even worse hack: the parsing error messages already say which character it expected (and what it got), so I just append the character it expects to the end and try parsing again. Rinse and repeat until it parses fully. The lines and their completions are short enough that this runs quick enough, despite being hugely inefficient (the entire line gets parsed again so many times).
3
u/fork_pl Dec 10 '21
Perl
No stacks, regexps ftw ;)
3
u/ThockiestBoard Dec 10 '21
Solution in Common LISP. Nice breather after a rough few days :)
Uses a stack-based validate function that returns the error character (for part 1) or the remaining character stack, if the string is exhausted (for part 2).
3
u/HAEC_EST_SPARTA Dec 10 '21
Erlang
Solution on GitHub
Working with stacks in languages that provide
[Head | Tail]pattern matching is always such a treat. Being able to specify both list traversals using solely pattern matching with no explicit control flow was pretty satisfying; I could even have combined both into one function, although that feels a bit too close to code golf for my liking.3
u/mxyzptlk Dec 10 '21 edited Dec 10 '21
3
u/BluFoot Dec 10 '21 edited Dec 10 '21
Ruby 181 bytes
I can't find a way to shorten the mapping in the first line...
3
u/polettix Dec 10 '21
Raku, nothing fancy.
3
u/Known_Fix Dec 10 '21
Python
The else block on for loops is an underappreciated feature:
3
u/relativistic-turtle Dec 10 '21
IntCode
Really enjoyed today's problem. Familiarity with stacks helped. Otherwise I might have attempted to solve with recursion... *shudder*.
For part 2 I had already implemented a merge sort algorithm in IntCode, so taking the median was easy.
3
u/VictorTennekes Dec 10 '21
Nim
Stack solution for both 1 and 2 in one loop. Any tips are welcome :)
3
u/[deleted] Dec 10 '21
C#
https://gist.github.com/thatsumoguy/23070ec9dda9f0de17bbb823486847aa
Part One wasn't bad once I figured out that C# allows for char math based off the unicode value. Part Two would have been easy but I kept getting stuck because I was trying to use int.....luckily long worked.
3
u/BestWifu Dec 10 '21 edited Dec 10 '21
Javascript
That lesson on stacks really came in handy.
Part 1
Part 2
3
u/4D51 Dec 10 '21
Racket
There's just something appropriate about writing a bracket-balancing program in a LISP dialect, isn't there? I wasted some time writing something that used 4 counters and considered
(<)>a valid string, before doing a stack-based implementation that ended up being simpler.3
u/Lispwizard Dec 10 '21
adventofcode day 10 in #emacs #lisp (#elisp) on android tablet under termux
3
u/nomisjp Dec 10 '21
Did it in Excel (no VBA) for parts 1 and 2 (up to column CQ!)
For part 1:
For part 2:
Was fun!
3
u/[deleted] Dec 10 '21
Haskell, fairly readable solution today, reminded me of the garbage problem from one of the earlier years
solution
3
u/radulfr2 Dec 10 '21
Python. Code is repetitive but didn't feel like refactoring.
3
u/Pille1842 Dec 10 '21
PHP
3
u/6745408 Dec 10 '21 edited Dec 10 '21
Sheets
I'm doing part two later on, but for part one, I did it with this gnarly formula
Not the prettiest thing. It could be cut down a bit... but not a lot :)
Part 2 has some hacky stuff -- but basically its flipping the dataset and running the same bullshit as everybody else. Should be 18 formulas all in, which isn't the worst.
3
u/khug Dec 10 '21
Literate CoffeeScript 1, 2
3
u/wfxr Dec 10 '21
Rust solution
3
u/frerich Dec 10 '21
Elixir
I still very much enjoy Doctest'ing these puzzles into submission.
For this particular case,
Enum.reduce_whilewas useful. I also appreciated the ability of list comprehensions to drop values which don't match a given pattern, i.e.3
u/aimor_ Dec 10 '21
MATLAB
Had a really fun time doing this in Matlab in matrices. Learned a neat trick for finding the first non-zero element in each row. Runtime is 7 ms with 5 of those being
regexprep, not sure if there's a better way to do that.3
u/loskutak-the-ptak Dec 10 '21
Common Lisp
This time I have experimented with the CL condition system.
3
u/feikesteenbergen Dec 10 '21 edited Dec 10 '21
SQL
Part 1 Explain Plan (22 ms)
Part 2 Explain Plan (28 ms)
3
u/SpaceHonk Dec 10 '21
Swift
https://github.com/gereons/AoC2021/blob/main/Sources/AdventOfCode/puzzle10.swift
again pretty straightforward with a simple stack of expected characters which made part 2 trivially easy
3
u/jayfoad Dec 10 '21
Dyalog APL
3
u/Mintopia_ Dec 10 '21
PHP
GitHub for logic. See also Day10 Task for getting the answer.
Spent around 15-20 minutes and took the popular approach of just putting the expected closing symbols onto a stack.
I'm really not wanting to get up at 5AM, so not in the running for speed, code golf or optimisation, just aiming to do a decent enough job to make maintainable code - even though this code doesn't need maintaining.
Average execution time over 1000 iterations, 14.9ms.
3
u/ecco256 Dec 10 '21
Haskell
3
u/fetshme Dec 10 '21 edited Dec 10 '21
Haskell
3
u/wzkx Dec 10 '21
Python
Simple, fast and dirty
3
u/dombo4life Dec 10 '21
Liberty BASIC
Quite happy with the result of today's puzzle! Had to implement my own hacky stack but it was quite doable, did not miss python that much this time around :p
3
u/Mrgglock Dec 10 '21
C
GNU C11, technically runnable in C++
Code
simple use of a deque
3
u/RibozymeR Dec 10 '21 edited Dec 10 '21
Factor
3
u/Skyree01 Dec 10 '21 edited Dec 10 '21
PHP
It was much easier than expected, I used a pile to store opening chars to make it super simple
Part 1
Part 2
3
u/mschaap Dec 10 '21
Raku, see GitHub.
After reading the first few sentences, I thought: this is a job for the awesome Raku Grammar functionality. Alas, that wasn't really an option since you need to do something with the results that don't match. Probably there is a way to do this, but I chose to build my own parser instead, that was easier.
Instead, I took this as an opportunity to use custom Exception classes, I hadn't done that before.
which made the main code pretty easy:
3
u/__Abigail__ Dec 10 '21 edited Dec 10 '21
Perl
Regexp time! First, we reduce the input by repeatedly removing pairs of open/close characters. Then, if the remaining string contains a closing character, it's a syntax error, and we get the first closing character to get its score. Else, we work our way backwards from the remaining string to get the score of an incomplete string:
Initialization:
Processing:
And printing the results:
(Am I bothered having variables
%scores,@scoresand twice a$scorein nested scopes? Not at all).Full program on GitHub.
3
u/Predator1403 Dec 10 '21
Excel
https://onedrive.live.com/edit.aspx?resid=93656A2289930448!53413&ithint=file%2cxlsx&authkey=!AP3s9XhA-cbuSSw
was quite simple today :)
3
u/Brief-Presentation-4 Dec 10 '21
c# Solution
3
u/dogsrock Dec 10 '21 edited Dec 10 '21
Beautiful puzzle today. After trying to track down these crazy brackets for a few hours, the 'aha' moment was truly satisfying.
My solution in Python here
EDIT: I haven't studied Stacks and now I realize there were quicker ways to do it! I just went about trying to collapse the pairs until none were left ¯_(ツ)_/¯
3
u/hrunt Dec 10 '21
Python 3
Code
After doing part 1, I really thought part 2 was going to be something more involved than what it turned out to be. I look forward to reading the inevitable regex solutions.
3
u/tenderspoon Dec 10 '21
My solution in Clojure. That was pretty easy for me, even though I'm still beginner!
3
u/Roras Dec 10 '21
Python
Got it very clean and tidy in the end
3
u/SvNNL Dec 10 '21
Python 3
Kind of forgot that stacks exist and decided to remove every occurrence of valid bracket pairs so the remaining string does not contain any valid pair. For Part 1, the first closing bracket in the remaining string is your wrong character, otherwise it's an incomplete line.
For Part 2, I take the reversed string of the incomplete line and add up the scores.
3
u/[deleted] Dec 10 '21
C
GitHub link
Works fast because it's C, but I'm sure there are better ways to implement this.
3
u/mockle2 Dec 10 '21 edited Dec 10 '21
python, both parts
3
u/ibiza_rupunzel Dec 10 '21 edited Dec 10 '21
Java Solution: https://github.com/justme789/Advent_of_Code_2021_Solutions_Java
Was struggling for a bit cuz I used int instead of long and kept getting the wrong middle value.....
Java part b solution:
3
u/shouchen Dec 10 '21
Pretty simple to read C++
https://github.com/shouchen/AdventOfCode/blob/master/aoc2021/Day10/Day10.cpp
3
u/French__Canadian Dec 10 '21
My solution in Q. Again, I used the a fold to do my loop. This has the downside of not exiting as soon as it finds the character, but i just add a flag to tell it to do nothing once if finds it.
I really like how in Q you can apply dictionaries like functions because in the mathematical sense, they both are mappings from input to output. So the dictionary
missing_ending_score:")]}>"!(1 2 3 4)is a dictionary, but it behaves exactly the same as if i wrote it as a function using a switch.3
u/[deleted] Dec 10 '21
Python, stack check
Part 1
Part 2
The program adds the opening character to a stack and pops them if a closing character meets the last one on the stack.
If that's not the case, it means the line is unbalanced
If the string ends and there are still characters on the stack, it means the line is incomplete
If the string ends and stack is empty, the line is valid.
Then it's a matter of checking what was the corrupted character for part 1, and what the remaining characters were on the stack for part 2
3
u/[deleted] Dec 10 '21
Javascript - Node
The solutions in my repository => Git
Or you can try it online at => Stackblitz
Greetings to all!
3
u/Atila_d_hun Dec 10 '21
C++
GitHub Solution
Conveniently
[,{,<counterparts can be matched because their ASCII value is+2. Annoyingly this is not the case for(and)which is+1.3
u/zndflxtyh Dec 10 '21 edited Dec 10 '21
Python3 - Uses a regex to scrub valid chunks from input lines
part1 is finding the first closing character in the corrupted lines, and scoring it.
part2 is found by scoring the corresponding closing characters to the opening characters in the incomplete lines.
3
u/[deleted] Dec 10 '21
Python
loved today's puzzle. I read the prompts and thought part 2 would be way harder but it was a satisfying problem nonetheless
https://github.com/rbusquet/advent-of-code/blob/main/2021/10/day10.py
3
u/goeyj Dec 10 '21 edited Feb 27 '26
[JavaScript]
Pretty standard stack solution. Nothing fancy to see here...
3
u/autra1 Dec 10 '21 edited Dec 11 '21
PostgreSQL
I managed to do it in idiomatic sql, without regexes and above all without recursive CTE \o/ (only allowing one for the score calculation of part 2).
code
plan part1
plan part2
EDIT: thanks to /u/williamlp I managed to remove the last recursive.
3
u/tmp_advent_of_code Dec 10 '21
I am getting much better at Rust. The more I use it, the more I am liking it
https://github.com/McSick/AdventOfCode2021/blob/main/10/parentheses-counting/src/main.rs
3
u/randomginger11 Dec 10 '21
Python
One of the rare ones where part 2 actually went faster than part 1
Did part 1 by keeping a list of each opening bracket we encountered, then if you find a character that doesn't match the last character in the list, it's invalid
For part 2, just make that same list and use it at the end of each line to calculate the score
3
u/TiagoPaolini Dec 10 '21
Python 3
I used a stack (last in, first out) to keep track of the open segments, then I compared if the closing marker matched the openings on the stack (in the order from last to first).
3
u/zatoichi49 Dec 10 '21
Python
3
u/curlymeatball38 Dec 10 '21
Haskell
3
u/AnalyticSquirrel Dec 10 '21
SQL (MariaDB) - No procedures, only SQL (and views)
https://github.com/tjbrinkman/AoC_2021/tree/main/10
3
u/c359b71a57fb84ea15ac Dec 10 '21
My Kotlin solution: [paste], [repo]
Today went pretty well for me, I only encountered some trouble trying to understand the scoring for Part 2. I was able to reuse the core of my solution in both parts with minimal adjustment, which is always nice:
3
u/wzkx Dec 10 '21
J (jlang)
3
u/OutOfNameException Dec 10 '21
F#
3
u/kf03w5t5741l Dec 10 '21
C
So I went for a recursive parser-ish option rather than a stack-based approach (is this a recursive descent parser?). The code's a bit shoddy, but the idea is to check if a code block is valid by:
Scan the remaining tokens until:
A closing character is found. In this case, check if it is the right closing character for our opening character:
This is probably a bit too long (140 LOC for the relevant bits) to be a neat solution but any feedback is welcome.
https://gist.github.com/kf03w5t5741l/7f9297307f2f4855c7e094f98caa12c1
3
u/Chrinkus Dec 10 '21
My C Solution
I used a stack to track my openers and compared the top to the next closer I found. That worked for part 1 but took me a bit to realize why I wasn't able to get an accurate score off of the remains of the stack for part 2.
The multiplication of the autotools points meant that the order of the remains were important! That and having to shift to a larger integer for the scores were the sneaky bumps for me on day 10.
My key to the solution was getting this right:
Lastly, any other Vim users ever accidentally abort a post trying to change from insert to normal mode?
3
u/roufamatic Dec 10 '21
Day 10 in Scratch. https://scratch.mit.edu/projects/614639850/
Stacks are pretty easy in Scratch, but the lack of local AND return variables with custom blocks is really starting to chafe!
3
u/occamatl Dec 10 '21 edited Dec 11 '21
Python:
3
u/[deleted] Dec 10 '21
Rust stack solution.
I'm just really beginning to learn the language
Part 1
Part 2
3
u/Meldanor Dec 10 '21
Elixir - a simple stack based solution.
Github: https://github.com/Meldanor/AdventOfCode2021/blob/master/lib/d10/challenge.ex
(Part1= run(1), Part2 = run(2). The input is read using a Util function which is inside the GitHub repo. The structure is to run the program
mix aoc 1 1to run the first day first part)3
u/dmrazor Dec 10 '21
Day 10: my C++ solution for part 2. Learned to use
for (auto : )loops today: Day 10, part 2, C++3
u/probablyfine Dec 10 '21
JQ
Time for recursion and pretending-a-list-is-a-stack! (Source and tests)
3
u/dizzyhobbes Dec 10 '21
Go solutions (all 320 stars)
https://github.com/alexchao26/advent-of-code-go/blob/main/2021/day10/main.go
3
u/apreche Dec 10 '21
Python 3
Very straightforward today. I love me some stacks.
https://github.com/Apreche/advent-of-code/blob/main/2021/10/syntax-scoring-2.py
3
u/WeddingMiddle1251 Dec 10 '21
Haskell
3
u/oantolin Dec 10 '21
Straightforward today, unless, I guess, you've never heard of a stack. Here's a Common Lisp program.
3
u/__Abigail__ Dec 10 '21
Blog post: Syntax Scoring (Perl)
3
u/u_tamtam Dec 10 '21
Another one for Scala,
I'm happy with my
checkerfunction which I could repurpose for both solutions,(false, List(first illegal character))(true, List(characters to match))so from there it was easy to partition the input and address each part on its own:
3
u/ywgdana Dec 10 '21
C# repo
It's always pleasant when I read a problem and immediately know how to solve it and just need to type. And realizing "oh this is just parsing a string using a stack" is a nice throwback to my university days!
3
u/KT421 Dec 10 '21
R
https://github.com/KT421/2021-advent-of-code/blob/main/dec10.R
Escape characters drive me nuts so I avoided the issue by using
URLencode().\\[is annoying, but%5Bis a perfectly innocuous string.It's not an elegant solution, but it DID work.
3
u/mgkhuie Dec 10 '21
Google Sheets still going strong: Day 10
3
u/odnoletkov Dec 10 '21
JQ
3
u/baer89 Dec 10 '21
Python
An easy one was nice for a Friday
Part 1:
Part 2:
3
u/areops Dec 10 '21
Javascript
3
u/qwesda_ Dec 10 '21
Postgresql
Part 1 GitHub explain.dalibo.com
Part 2 GitHub explain.dalibo.com
I'm pretty late today ...