r/adventofcode • u/daggerdragon • Dec 08 '21
SOLUTION MEGATHREAD -ð- 2021 Day 8 Solutions -ð-
--- Day 8: Seven Segment Search ---
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:20:51, megathread unlocked!
72
Upvotes
93
u/4HbQ Dec 08 '21 edited Dec 08 '21
Python, using digits with known lengths as masks. Take the last case for example: a digit with
must be a '0'. Then simply add and repeat:
43
u/qualorm Dec 08 '21 edited Dec 09 '21
Here's a diagram which you can use to ALWAYS determine which segment is which.
Also, my solution in Python.
32
u/logiblocs Dec 08 '21 edited Dec 09 '21
Interesting approach (any language):
There's a scheme to normalise the input signals so you can just do a hashmap lookup.
Count the number of times each signal character appears across all signal patterns.
For example, for the gold-standard signal map it's:
Then replace each signal character in the pattern with its count and sort. This will be unique for each digit and consistent across cases.
Edit: did not realise code was required, Python
23
u/DonKult Dec 08 '21 edited Dec 09 '21
Debian packages (aka:
apt-get install solution)(edit: I wrote a blogpost explaining idea, theory and implementation a bit for those interested in this particular one or solving it via generic solvers in general)
Part 1 you have to do on your own, but if you don't want to write a well thought out solution for Part 2, we can let good old
aptdo the busy work and ask it to find the output values given all the constrains provided by the segments. On the example given in part 2 it will e.g. dutiful report:With this we only need a bit of shell to extract the output numbers and paste them into
bc, e.g. so:parallel -I '{}' ./skip-aoc '{}' -qq < input.txt | paste -s -d'+' - | bc. The scriptskip-aoc(paste) is written as a testcase foraptitself and so needs to be placed in/path/to/source/of/apt/test/integrationand apt be built â I am not using any unreleased features so the system installed one could be used instead, but writing a standalone script is busywork I wanted to avoid for myself.Now, sit back for a few minutes and let
paralleloptionally grill your CPU (you may want to use-P). There is tremendous optimization potential, but that is left as an exercise for later. A single number is printed at the end: It is your solution for part 2!Note that I am not using the default resolver, but
aspcud, which is used e.g. by Debian for building packages targeting experimental and/or backports. There are other resolvers available which probably can deal with this as well. We might even get new ones sooner or later (there is some PoC for a z3 based one). With a redesign of the problem definition we could probably convince the default resolver to solve this conundrum, but in the end the very heuristics deployed to make it usually work better on "normal" problems than SAT and similar solvers can bite us while solving Advent of Code puzzles.Disclaimer: No cows were harmed in this solution.
20
u/nthistle Dec 08 '21
Python, 6/5. Best day so far this year! I just did the quick and dirty "brute force through every permutation" after doing some back of the napkin math to make sure it'd be fast enough. Takes like ~10 seconds to run (Yes, I know, I should be using PyPy).
18
u/frankbsad Dec 08 '21 edited Dec 08 '21
I'm pretty happy with my solution for today. Realised all you need to know is one and four and determine the rest from that
Rust
full solution : Github
23
u/4HbQ Dec 08 '21 edited Dec 08 '21
Python, golfed down to
187185 bytes, thanks to /u/Peter200lx!The main trick is to count the number of segments a digit has in common with '8', '4' and '1', hash these counts to a small unique number (here it is x*y+z % 16), and then use it to find the digit in this string
53460_1_7_92__8.Update: down to 128 bytes, based on a related observation from /u/logiblocs and /u/lbm364dl.
11
u/bluepichu Dec 08 '21
TypeScript, 10/23. Code here. I didn't think of just brute forcing the permutation until after solving it, but hey, I'll gladly take 23rd!
11
u/Mathgeek007 Dec 08 '21 edited Dec 08 '21
Excel. 1581/2673.
So. How the heck is this doable in excel? Brute fucking force.
I started by assigning each letter to a number; A=1, B=2, etc. Then I converted each to a binary expansion, then compressed it into a decimal number.
Find the number with only 2 segments. Call it 1.
Find the number with only 3 segments. Call it 7.
7 xor 1 is the top segment.
Find the numbers with 6 segments. These are 0, 6, 9. Find the odd one out when xor with 1. That number is 6.
Find the number with 7 segments. Call it 8.
8 xor 6 is the top-right segment.
1 xor top-right is the bottom-right segment.
Find the numbers with 5 segments. These are 2, 3, 5. Using top-right and bottom-right and xor, you can identify these numbers.
3 xor 5, xor BR. This gets us top-left.
3 xor 2, xor TR. This gets up bottom-left.
8 xor bottom-left, call this 9.
Now we have 6 and 9, uniquely find 0.
0 xor 8 gives us the middle segment.
8 xor all the segments gets us the bottom segment.
Take all the segments, find the binary representations of each number, and create a lookup table. Lookup, concat, add, done.
VIDEO OF SOLVE
Also, hey! If you're a spreadsheeter too, hit me up! We have a Discord and a leaderboard if you want to compare yourself to other Excel-lent sheeters!
10
u/mstumpf Dec 08 '21 edited Dec 10 '21
Rust, based around the fact that sum of histogram values of the signals are unique.
Inspired by https://www.reddit.com/r/adventofcode/comments/rbj87a/comment/hnpad75.
10
u/kbielefe Dec 08 '21
Scala 3
Made a lookup table of (length, number of overlaps with '1', number of overlaps with '4'), which is enough to uniquely identify any digit. Didn't decode the actual segment mapping.
10
u/systolicarray Dec 08 '21
Clojure, source and tests.
I managed to come up with an approach that re-encodes each input/output value using the frequency of each segment. Here's a diagram illustrating the frequency of each segment:
Re-encoding requires two steps: first, calculate the frequencies of each character over all input values and then replace each character with its frequency and sort the result (e.g.
acedgfbbecomes4677889).Each input/output value can then be decoded using a pre-computed hash map:
8
u/PerturbedHamster Dec 08 '21
Language? Language? I don't need no stinkin' language. Well, I do, but my SO doesn't. Here's her part 1 from the command line:
cut -d "|" -f2 input_20211208.txt | grep -o -E '\b\S{2}\b|\b\S{3}\b|\b\S{4}\b|\b\S{7}\b' | wc -l8
u/[deleted] Dec 08 '21
[removed] â view removed comment
8
u/zniperr Dec 08 '21
python3:
Is it just me or was the problem description exceptionally hard to read today? I spent like half an hour just figuring out what the input was.
15
u/SuperSmurfen Dec 08 '21 edited Dec 08 '21
Rust (7425/298)
Link to full solution
This ð has to be the strangest leaderboard placing ever. I more or less skipped reading part 1 and just assumed what the problem was, so stupid... What I actually started solving turned out to be part 2. After I got an answer for part 2 I realized that wasn't what the question was asking. Luckily my "assumption" for what part 2 would be was correct so I gave the correct answer immediately after part 1!
And, my best placing so far this year, top 300! I went for a very naive solution but it was fast to implement. For each display, just try all
7!permutations of wires and see which works. That is5040per display and there were only200displays, easily bruteforceable.Map each char to the char in the permutation, and see if for all digits they match any of the expected:
Finishes in about
350mson my machine.15
u/scmbradley Dec 08 '21
Python
Genuinely quite proud of this solution. It exploits the fact that each number has a unique pattern of "occurence numbers" for how many times its segments appear in the digits 0--9.
Here
7
u/cwhakes Dec 08 '21
Rust
The second part was a doozy. Starting with 1, 4, 7, 8:
I'm just glad there were no missing digits.
7
u/voidhawk42 Dec 08 '21
APL, input was small enough to brute force with all permutations of
abcdefg:7
u/relativistic-turtle Dec 08 '21
IntCode
Phew! Quite the challenge today. Took some time to process the puzzle-text, but other than that Part 1 was straightforward. For Part 2 I think I laid out a strategy with minimalistic and clever logic to identify the segment and reconstruct the numbers. Still was very finicky to implement. Very satisfying when I succeeded though :).
Segments were identified by counting in how many of the 10 digits they appear, and whether they appear in the "4". These 2 pieces of information was sufficient.
(Note: assumes 200 lines in input).
7
u/nidrach Dec 08 '21 edited Dec 08 '21
Java part 2: I get the frequency of each character and then replace the character with the frequency. The sum of the frequency is different for each number of the display.
7
u/StingGhost Dec 08 '21 edited Dec 08 '21
My solution in Python. The trick I found to part 2 was to calculate a fingerprint that is unaffected by the scrambling. I then calculate the fingerprint for the unscrambled digits, and use this to look up the correct digit from the scrambled data. This is part 2:
https://github.com/kolonialno/adventofcode/blob/main/nnerik/08/solve.py
7
u/ViliamPucik Dec 11 '21
Python 3 - Minimal readable solution for both parts [GitHub]
6
u/jayfoad Dec 08 '21
Dyalog APL
The tricky bit here is f which takes a boolean matrix representing which encoded digits (the rows) contain which randomised segments a through g (the columns), like this:
... and comes up with a canonical reordering of the rows, regardless of how the columns are permuted, like this:
The ordering it uses is:
1 1 0 1 1 0 1is preferred because it has only 1, 2 and 2 segments in common with each of the first three rows already chosen, and1 2 2is lexicographically smaller than the result you get by doing this for any of the other five-segment rows.Then it's just a fixed mapping from this canonical ordering back to the real digits that these rows represent.
6
u/ecco256 Dec 08 '21
Haskell
6
u/__Abigail__ Dec 08 '21
Perl
First thing I did was read the input, and normalize the entries: I sorted the used segments in each entry so I could quickly look them up:
I then group the
@inputlist on their lengths:This leads identifying our first four digits. We use an array
@digitswhich maps the digits to the segments they use:To distinguish the rest, we need a helper function, which takes two sets of segments, and returns the number of segments they share:
Next, we distinguish between 0, 6, and 9, which all use six segments. The 6 shares one segment with 1, while 0 and 9 share two. 0 shares three segments with 4, while 9 shares four:
And then we can do a similar trick to distinguish between 2, 3, and 5, which all have five segments. 3 shares two segments with 1, while 2 and 5 share one. 5 shares five segments with 9, while 2 shares four segments with 9:
Now we can make a simple lookup table which maps sets of segments to the number they will display:
Getting the answers for part one and part two is now simple:
The complete solution is on GitHub.
6
u/williamlp Dec 08 '21 edited Dec 08 '21
PostgreSQL
I did it with temporary tables and multiple queries using some bitwise operators to detect digits. It could be cleaned up or combined into a single query with CTEs but I was happy to just get there. :)
https://github.com/WilliamLP/AdventOfCode/blob/master/2021/day8.sql
6
u/Smylers Dec 08 '21
Perl, using
Set::Object. The full code is pretty short, but here are the most interesting bits:Reading in the input involves calling
split3 times on each input line, to split by the vertical bar, then splitting each half of that into digit clusters, then splitting each cluster into individual letters, for forming a set:Group each pattern by size:
Then create a hash mapping each pattern to the digit it represents, by iterating over a list of specs for the digits:
That block inside
pairmapâ which, handily, was one of thoseList::AllUtilsfunctions I was trying out yesterday â gets each digit in$aand its spec as a hash-ref in$b.The first four digits are identified just by size. Then 9 is the size-6 pattern which is a superset of 4's pattern. And so on. 6 can be defined as the only size-6 pattern, because by then the others of that size have been allocated. So the above list is all that's needed to uniquely identify them.
extract_first_by(also fromList::AllUtils) does what it says: returning the first item in the group that meets the specified criteria, and also removing it from the array, reducing the candidates to allocate next time through.%barsis the opposite of%digit: it gives the set of bars for a digit. It's only used inside thepairmap, for the super- and subset relationships. Having assigned a set to$bars{a}, that value goes on the left of the=>that forms the pair returned from the block.It'd be straightforward to make this solve part 1 as well, but I didn't bother because I'd already solved that in Vim.
In case it's of interest to anybody else, here's a quick comparison of some set modules available on Cpan, which I ended up reviewing as a side-effect of writing the above code:
Set::Lightdoesn't have a serialization method, something which is needed for using a set as a hash key.Set::Tinyhas an->as_stringmethod, but it needs to be invoked explicitly, which isn't as handy as just turning into a string when requiredSet::Objectis mentioned as being slower in the docs of both of the above two modules, but it was the most convenient to use and was fast enough, so it's what I went with.Set::Scalardoes have implicit stringification but doesn't have thesetfunction as a constructor that the above two provide, making constructing a set a bit less elegant. AndSet::Tinysays it's even slower thanSet::Object.6
u/NeonPuzzler_ Dec 08 '21
Python 3.9 Golf
Part 1: One line - 73 bytes
Part 2: One line - 173 bytes (Improvement on u/4HbQ)
6
u/nicuveo Dec 08 '21
Haskell
6
u/-vest- Dec 08 '21 edited Dec 08 '21
Excel
I apologize, probably for off topic, guys & gals. I am not the leader in the speedy solutions, but I have a question:
Is anyone interested in my solution in Excel (no VBA, of course)? If yes, I can share my file with you (no macros, no viruses), or you can just see my screenshots of the second part that I am not lying :)
https://i.imgur.com/i6ZcX4t.png
p.s. I was trying to upload my solution to Google Docs, but it doesn't like few Excel's formulas.
p.p.s. you can download my file here, or check it online: https://docdro.id/RjFwRCf
5
u/jonathan_paulson Dec 08 '21
Pypy. 49/25. Video of me solving.
Neat problem! I implemented brute force for part 2. I also decided to implement a smart/fast solution for part 2. As a result, this is by far my longest video so far this year :) I included both the brute force and smart solutions in the code above, so you can compare.
The simple solution was faster to think of, faster to write, and less code (although arguably more complicated code), but runs much much slower. For speed, the simple solution was clearly the way to go. But working and implementing the logic for the fast solution was fun :)
5
u/obijywk Dec 08 '21
Python 3, using https://github.com/Z3Prover/z3 to find a satisfying assignment of segments for each line of input.... which is terribly slow (it's still running), and stressing my CPU fans, but I believe it will work!
5
u/RodericTheRed Dec 08 '21 edited Dec 08 '21
Python3
5
u/MasterMedo Dec 08 '21
Python 505/180 featured on github
5
u/seba_dos1 Dec 08 '21 edited Dec 08 '21
Python 3 (both parts, no imports, 8 lines, 435 characters)
5
u/Smylers Dec 08 '21
Vim keystrokes for part 1 is a one-liner:
The number of lines remaining is the answer.
That's 8 out of 8 days so far in which I've managed to solve at least part 1 in Vim. At some point this is going to run out, surely ...
5
u/NohusB Dec 08 '21 edited Dec 08 '21
Kotlin
5
u/EmeraldElement Dec 08 '21 edited Dec 08 '21
I'm using AutoHotkey (imagine that). It's my language of choice for some reason.
I decided not to brute-force 08 because I saw a path to deciphering the jumble and it worked! Reasoning below:
-Length 2 string is unique (cf) and its two characters respectively appear 8 times in the list (c), and 9 times (f).
-Length 3 string is unique (acf) and includes the same (c) and (f) as above so the remaining character becomes (a).
-Length 4 string is unique (bcdf) and includes the same (c) and (f) and the remaining two characters, one of which appears 6 times (b) and the other 7 times (d).
-Length 7 string is unique (abcdefg) and includes the remaining two, (e) which appears 4 times and (g), which appears 7 times and is not (d) from above. I didn't optimize this part because it would have taken some rewriting so I just stored the translated (d) character from the length 4 string and chose the other character that also appears 7 times.
https://github.com/Emerald-Element/aoc2021/blob/b6b7a233be9eab05ffc2d3f6cb3842cbc08de9f6/aoc2021_08b.ahk
5
u/rmbolger Dec 08 '21
PowerShell. Part 1 was nothing to write home about. Part 2 uses the following codified rules to determine the unknown digits.
And here's the code for both parts which assumes the puzzle input is in the clipboard. Not the most terse thing in the world, but it's nice and fast especially if you remove the
Write-Verbosestatements.5
u/Diderikdm Dec 08 '21 edited Dec 08 '21
Python:
5
u/TinBryn Dec 08 '21
Not a complete solution, but the logical core of part2 in Rust
5
u/DFreiberg Dec 08 '21 edited Dec 09 '21
Mathematica, 160 / 685
Very unsatisfying brute force; I trimmed it down from the initial 65 second runtime down to 2.7 seconds, but it's still brute force, and obviously does not scale. I then spent another two hours trying to find a perfect Mathematica solution via graph theory, like
FindIndependentEdgeSet[]for last year's recipe problem; it ought to be possible to represent all of the possibilities for each letter from each word as a graph, and then use graph intersections somehow to filter through for an arbitrary number of possibilities and rules...but if any such built-ins exist, I couldn't figure it out.Setup:
Part 1:
Part 2:
[POEM]: Constraint Problem
The caves and segments both constrain
Where we are apt to go,
And like the tracks that turn a train
Our course is set, we know.
Constraints leave but a single route:
The segments made it clear.
So since we're stuck until we're out,
I hope the keys are here.
5
u/xoronth Dec 08 '21
Turing
Code
Yes, this is a language. Shoutouts to any Canadians who have also used this thing in high school.
5
u/emu_fake Dec 08 '21 edited Dec 08 '21
C#
just posting the mapping for part 2 as the rest is trivial:
Edit: You have to sort each signal pattern (a->f) to get this solution working
5
u/rf314 Dec 08 '21
Python
I like how readable part 2 is to me.
5
u/clouddjr Dec 08 '21
Kotlin
5
u/javier_abadia Dec 08 '21 edited Dec 08 '21
Python
Using lengths to identify unique digits. Then we are left with two sets: digits that may be 2,3 or 5 (with 5 segments) and digits that may be 0,6 or 9 (with 6 segments).
Using set intersections we can use other known digits to calculate how much they overlap. For instance we know that between 0,6 and 9, only 6 overlaps exactly one segment with digit 1, so we can find 6. Also overlapping 9 with 4 we should get 4 common segments. And then 0 is the other one.
A similar logic is used to find 2,3 and 5.
5
u/Nerdlinger Dec 08 '21 edited Dec 08 '21
Swift
I'm sure I can clean up my part 2, but it works, and it works swiftly, so we'll see how much I bother to think about it.
edit: I cleaned it up.
5
u/WayOfTheGeophysicist Dec 08 '21
Python 3.9
Can't install 3.10 yet. That match-case solution by /u/4HbQ is beautiful!
I didn't like the idea of trying every permutation, so I just sorted my inputs. That gives a couple neat exploits.
For Part 1 I simply counted the digits that were allowed, easy enough. I knew this wouldn't work for part 2 but sometimes you have to just take what you can get.
Here I was able to exploit the order of the digits.
1,4,7,8are always in the same place. Then I used the geometry of the 5-element and 6-element groups to find the missing numbers. E.g. 9 is the only number that perfectly contains 4, and work from there.Full code here.
5
u/__Abigail__ Dec 08 '21
Blog post: Seven Segment Search (Perl)
5
u/RewrittenCodeA Dec 08 '21
Elixir - part 2 using graph isomorphism. The translated digits have the same "subset" relation as the original ones, so we only have to count how many digits are subsets and supersets of the given ones.
5
u/j3r3mias Dec 08 '21
Solution using python and Z3 (theorem-prover). My solution is:
The solution is too slow (15 seconds per problem in my slow machine) because of the number of constraints (only after I finished my solution, I realized that bruteforce would be faster because of the number domain to search).
5
u/qwesda_ Dec 08 '21
Postgresql
Part 1 GitHub explain.dalibo.com
Part 2 GitHub explain.dalibo.com
This is the first version I found ...
5
u/Toanuvo Dec 08 '21
j solutions
https://github.com/Toanuvo/Advent-of-code-2021/blob/main/J/day8.ijs
5
u/Maolagin Dec 08 '21
Python
This puzzle was one where iterative code noodling didn't help at all - but once I spent an hour writing down set relationships the solution just about wrote itself. This descrambler function solves the puzzle input in 4.5 - 4.8 ms.
5
u/lbreede Dec 08 '21
Python3, basically writing code while coming up with the solution step-by-step, therefore incredibly messy and redundant at times, but working!
5
u/thibpat Dec 08 '21
I've recorded my JavaScript solution explanation on https://youtu.be/ueceglwuUGM
The code is available on github: https://github.com/tpatel/advent-of-code-2021/blob/main/day08.js
5
u/_rabbitfarm_ Dec 08 '21
Perl solutions.
Part 1 https://adamcrussell.livejournal.com/32026.html
Part 2 https://adamcrussell.livejournal.com/32296.html
5
u/azzal07 Dec 08 '21 edited Dec 08 '21
Awk (sorry, another for the day)
I've found myself gravitating back to "golfing" these with awk, even though I'm using Postscript as my main language for the year.
I'd like to note few things about the code:
1/8 ~ (length - 2). This works because1/8 = 0.125which includes all of the unique lengths and no other.index(table, f)allows omitting one digit from the table, sinceindexreturns0if not found. This also removes the annoyance of 1 indexing, which would require offsetting after the modulo. The functionfis the same as in my Postscript solution. And the table is just inverted so thattable[k] = vbecomestable[v] = k.5
u/Imaginary_Age_4072 Dec 09 '21
I made another solution (Common Lisp) which I like better than my original one, even though there's more code supporting it (https://github.com/blake-watkins/advent-of-code-2021/blob/main/day8.lisp). The essential functions are:
guardspecifies a condition that needs to be true, so the line(guard (= 1 (num-intersections-with six one)))means that whatever word was picked for six has to share 1 segment in common with whatever word was picked for one. Since six is the only number with 6 segments that this is true for (nine and zero both share 2 segments with one), the proper word will have been picked.amb(in the pick function) is an implementation of McCarthy's nondeterministic operator (https://ds26gte.github.io/tyscheme/index-Z-H-16.html#TAG:__tex2page_chap_14) which picks a value from a list "ambiguously" - the value it returns is guaranteed not to cause a subsequentguardform to fail.Behind the scenes it's essentially doing a dfs search with backtracking - any time one of the
guardforms would fail the code goes back to the most recent choice point and tries again.At the bottom is a continuation and state monad - the state is the list of unpicked patterns in this case. Above the monad is an implementation of
call/ccto access the continuations, and thenambis on top of that. The code is here (https://github.com/blake-watkins/advent-of-code-2021/blob/main/game.lisp) - it's called Game monad since originally I used it to solve the game in AoC 2015 Day 22.5
u/stevelosh Dec 09 '21
Common Lisp: https://github.com/sjl/advent/blob/master/src/2021/days/day-08.lisp
Didn't have time for anything fancy today.
5
u/CCC_037 Dec 09 '21
Rockstar
Sorry this took a while; Part 2 put up a lengthly fight.
Part 1:
Part 2:
It put up a lengthly fight, and it is lengthly code.
https://pastebin.com/hSSXNcBB
5
u/skawid Dec 14 '21
Python!
Got a really nice solution for day six, so of course I was due a horror show like this one...
0
u/[deleted] Dec 08 '21
[deleted] â view deleted comment
4
u/InflationAaron Dec 08 '21
Rust
A bit of set operations
4
u/isukali Dec 08 '21 edited Dec 09 '21
C++ Solution: P1 was easy enough, but I am surprised that I haven't seen a solution that solved P2 like I did, they're all intersections!. Not sure, but maybe my method is slower?
P2:
4
u/mebeim Dec 08 '21 edited Dec 09 '21
2837/748 - Python 3 solution - Walkthrough
Coolest puzzle yet this year so far IMHO! Logical deduction puzzles are always cool. I did part 1 pretty slowly because I was trying to be smart and predict that we actually needed to store those sorted/hashed strings for part 2, and I realized too late that it would have taken much more than simply checking the length. Oh well, at least my part 2 timing was not that bad. PS:
frozensetFTW.4
u/q3w3e3_ Dec 08 '21
Google Sheets
4
u/tuvok86 Dec 08 '21 edited Dec 08 '21
This was pretty easy, well...explanation was very contrived and more of a logic challenge than a coding one, but I'll take it...my p2 solution in javascript/js:
4
u/pushkar8723 Dec 08 '21 edited Dec 08 '21
JavaScript
https://github.com/pushkar8723/AoC/blob/master/2021/8/1.js
I didn't do brute force. Instead, I figured that if I just count the occurrence of each character in the first part of the input, I can figure out 3 segments uniquely.
So let's say I represent my segments positions as
If I check how many times each segment will turn on to show 0 - 9 once I come to the following conditions:
So, if I just count the character's occurrences in the first part of each line, then I can figure out segments 1, 4, and 5 as each of them has a unique turn-on value.
For, top (segment 0) I can check missing char in digits 1 and 7. Hence, I also now know segment 2.
For, middle (segment 3), I just need to check unknown char in 4.
So, the last remaining char represents segment 6.
4
u/Melocactus283 Dec 08 '21
R / Rlang
Decently clean and functional
4
u/omnster Dec 08 '21
Mathematica
Input
Part 1
Part 2
Long and ugly
This proceeds to figure out which letter corresponds to which wire by comparing sets that form different digits.
abanddis the difference between one and four.a,d, andgare the wires that are shared by digits two, three, and fivedis the intersection ofbdandadgbis what remains inbdafter we removedgis the complement toadinadgbso we can pick the five from the input which gives usabdgfand then removeabdgto obtainfcis what remains from ones (two-letter lists) after removingfeis the only remaining one, we get it by removing everything codingabcdfg.This function takes as input the sequence before
|and outputs a list of the letters in the order that codesa,b,c,d,e,f,gThere is a helper function
pickLenwhich picks frominputlists of the lengthlengthThen we convert the coding sequence into numbers
Here
wiredigis a function that works somwehat likewiredig[{"a", "b", "c", "e", "f", "g"}] = 0, wiredig[{"c", "f"}] = 1, ....Finally, the answer
4
u/JustinHuPrime Dec 08 '21
x86_64 assembly
Part 1 wasn't too bad- I decided against parsing the strings and just counted based on string length.
Part 2 was extraordinarily challenging. On the suggestion of a friend, I used integers as a way to store which segments are on. I could then perform set operations on that set using bitwise operators. I still had to consult my friend's solving algorithm to get anywhere though, so credit to my friend for a very elegant solution. I did have to remember that the inverse of a set needed to have its first bit masked off.
4
u/Dryctas Dec 08 '21
Bash
Part1:
https://github.com/honzatlusty/advent-of-code-2021/blob/master/8/program.sh
Part2:
https://github.com/honzatlusty/advent-of-code-2021/blob/master/8/program2.sh
No real system behind this one, I basically test how many characters are different between the sequences, knowing what numbers could fit that.
4
u/lbm364dl Dec 08 '21 edited Dec 08 '21
My solution in Python. It looks like today's problem had lots of different approaches. After writing an ugly code I tried again and noticed that the sum of the number of times each letter appears is unique for each number, so, for example, if an entry sums 42, we know it's the number 0, because in the original arrangement it is the only number that sums 42. This idea doesn't use the lengths hint from part 1. I hope the comments help.
4
u/leftfish123 Dec 08 '21
Here's my approach (I have no CS background) in Python. In short:
- assume that each line uses all 10 digits [they did in my input]
- identify the easy ones (1, 4, 7, 8) by length
- check 'sixes': the one with letters from 4 must be 9, the next one with letters from 1 must be 0, the remaining must be 6
- check 'fives': the one with letters from 1 must be 3, the one that is one letter away from 6 must be 5, the remaining must be 2
Voila. I guess this is as raw and brute as it gets, so I'm about to make a dive into this thread to see what other people came up with.
4
u/snurre Dec 08 '21 edited Dec 08 '21
Kotlin
4
u/jitwit Dec 08 '21 edited Dec 08 '21
J Programming Language
4
u/statneutrino Dec 08 '21
Python 3 solution using frozen sets as dictionary keys. Part 2 runs in 5ms
https://github.com/statneutrino/AdventOfCode/blob/main/2021/python/day8.py
4
u/LennardF1989 Dec 08 '21 edited Dec 08 '21
C# / CSharp
Part 1
https://github.com/LennardF1989/AdventOfCode2020/blob/master/Src/AdventOfCode2021/Days/Day08.cs#L12
Part 2
https://github.com/LennardF1989/AdventOfCode2020/blob/master/Src/AdventOfCode2021/Days/Day08.cs#L32
I commented my methods of deducting the numbers :)
EDIT: In hindsight I don't need the int.Parse, but could instead use something like:
numbers.IndexOf(n) * 1000 + numbers.IndexOf(n) * 100, etc.4
u/rakkie20 Dec 08 '21
Rust
Utilizing the fact that we can decode numbers by counting the total amount of line segments in the signal and the overlap with either the signals for '1' or '4' (which we know based on just the length).
4
u/Enculiste Dec 08 '21
Python
Quite happy with this one as it is plain Python3 using only dicts, strings and list comprehension. Left it explicitly verbose and with comments for the curious. A bit slow (24ms) and could be optimized but written in less than 1h so that is ok I guess.
4
u/theSpider_x Dec 08 '21
C solution.
Written a lot of stuff on paper but my solution was that you could deduce certain segments to two segments from the given 1, 4, 7, 8 digits. Then you can find digit 3 which resolves 4 segments so there are two remaining unknown segments but now you can search for digit 2 and from that deduce the last two segments.
Runs in like 1ms
https://github.com/fuzesmarcell/aoc_2021/blob/main/day_08.c
4
u/SplineGopher Dec 08 '21
GOLANG
https://github.com/Torakushi/adventofcode/blob/master/day8/day8.go
simply get easy number (8,7,1,4) then, "subsctract" number in string format:
For exemple take 6 letters number (6,0,9), "substract" the string representation of 1, if the substract as a length of 5, then it is the representation of 6, ... :)
4
u/levital Dec 08 '21
Haskell
Ah, back to the old "solve this trivial parsing question for part 1 and then do everything else in part 2"... My solution is incredibly dumb and I'm pretty embarrassed that this code now exists online with my name attached. But I guess it works...
4
u/radulfr2 Dec 08 '21
Python. I liked this task. What I didn't like were the stupid mistakes I kept making :D
4
u/wfxr Dec 08 '21 edited Dec 08 '21
Rust bitwise solution:
4
u/azzal07 Dec 08 '21
Postscript, PS.
After some
careful analysis aimless exploration, I managed to find perfect hashing (no empty slots) for the digits. Using only the segments common with 1, 4 and 8 (i.e. the # of segments).Here is the mapping:
4
u/oantolin Dec 08 '21 edited Dec 08 '21
Shortish (~30 lines) brute force solution, testing all permutations of
abcdefgin Perl.4
u/colombo15 Dec 08 '21
C#
Used a bunch of .Except() methods with char arrays
github
4
u/compdog Dec 08 '21 edited Dec 08 '21
Javascript [Part 1] [Part 2]
Part 2 was one of the hardest AOC puzzles that I've ever done. I don't think that it should have been this hard, but it was. I kept getting confused about which way my mappings worked (scrambled -> real versus real -> scrambled). I also spent way too long trying to code a purely analytical solution before I finally realized that I could just get "close enough" and then brute force the rest. So that's what I did. My part 2 solution works like this (for each input separately):
bruteForceRemainingG(the terminal case), a mapping object is created and stored in an array. Then the next configuration is tried, and the next, until every possible configuration is stored in the array.I'm sure there are better ways to solve this, but my solution works and I'm happy with it.
4
u/French__Canadian Dec 08 '21 edited Dec 08 '21
My solution in Q. Part 2 runs in 6ms. I created set operations for creating the mapping and just sorted all the letters at the end to do the exact matching.
I really scratched my head while trying to find why my program was crashing and then realized it was because I was using the mapping variable in embedded functions but Q does not have lexical scoping so it just could not access the mapping. Ended up using midline variables which would probably get you murdered by your colleagues if you did that at work, but in a way it is very apl-like.
I do wish Q had lexical scoping
4
u/Extension_Wheel_2032 Dec 08 '21
Clojure, brute force is plenty fast:
4
u/Kamik423 Dec 08 '21 edited Dec 08 '21
Python
I created a mapping matrix and found a way to normalize the matrix by swapping rows and columns until it reached a standard form. Thus I could correlate code words to numbers. GitHub with commented code.
The normalization first sorts the rows and columns by number of items in them. Then it repeatedly sorts them as fit hey were binary numbers. Multiple passes are required as rows and columns interleave and sorting columns changes each row's value and vice versa. The sorting-by-count is required as otherwise they don't converge to the same solution. I cannot prove it always works; In my case however all inputs result in the same matrix.
The nice thing about this is that if it indeed reliably works it could quite easily be adapted to different display configurations.
4
u/probablyfine Dec 08 '21
JQ
(Source and tests)
Rather than try to figure out a smart way, I opted to enumerate the entire state space of possible wirings, use the left hand side of the input to look up which wiring it was, then used that to derive the value of the right hand side.
It only takes ~ 5-6s for part 2, which is totally fine for brute force, and there's optimisations that I could make.
4
u/vegapunk2 Dec 08 '21
Python 3
It was long to figure it out but paper and pen always end up finding the solution.
part 1 and part 2
4
u/j4nd8r Dec 08 '21
Scala 2.13
Nice challenge and reminded of the days I was taught Prolog in University. But I'm afraid I did not really solve it the prolog way. Instead a very dirty solution in Scala, looking at sizes and being subset of earlier patterns. Found some nicer examples in other repos.
4
u/SV-97 Dec 08 '21
Fun (and fully vectorized) implementation in Python https://github.com/SV-97/AdventOfCode2021/blob/main/Day_08_2/main.py
I went a bit harder on the linear algebra today: we may interpret our 7-segment display as a 7-dimensional vector space over Z/2Z. Just identify a with e_1, b with e_2 and so on. This way the problem is reduced to solving PV = W (or VP=W - I'm not quite sure right now) where V is a matrix containing the encoded digits in the "right" way and W a matrix containing the encoded "wrong" digits. Once we know P just apply it to (or it's transpose depending on how you solve the problem) to the matrix of the encoded right hand sides and decode.
4
u/AOC_2020 Dec 08 '21 edited Dec 08 '21
Finding all positions by applying set intersections and subtractions.
Finally applying regexes to each display output in Kotlin (golfed):
0
u/[deleted] Dec 08 '21
[deleted] â view deleted comment
4
u/SnooConfections2453 Dec 08 '21
My solution in ruby: https://github.com/ciscou/aoc/blob/master/2021/08.rb
As always, trying to make the solution both compact and readable.
4
u/zxywx Dec 08 '21 edited Dec 08 '21
Ruby
4
u/phaazon_ Dec 08 '21 edited Dec 08 '21
Rust solution, which was pretty fun to code, especially part 2. :)
To sum up the idea, (spoilers!) we have 4 unique patterns for 1 (only one single pattern of length 2), 4 (length = 4), 7 (length = 3) and 8 (length = 7). We just need to look for those patterns first and store them in a simple map (an array of String with 10 elements, initialized with empty strings; a non-empty string means the pattern was found). Then, we can deduce which are the next ÂŦ deducible Âŧ patterns. 9 is easy to find because itâs the only 6-length pattern that contains both 4 and 7. 3 is easy too, since itâs the only pattern of length 5 containing 1. Then, for 2, itâs the only pattern of size 5 that 9 doesnât contain. For 5, itâs the last missing 5-size pattern. Then we have 6, which contains both 5 and 9. And finally, the remaining missing pattern is obviously 0.
Once we have this information, we can reverse the array to build a string -> int map, and iterate over the output value. Itâs important to lexically sort both the keys of the map and the output value to be sure the wires are all expressed the same way. Then look up the output values in the digit maps, and rebuild the number before summing them (fold over the digits and n = n * 10 + digit. Done.
Probably one of the most exotic and fun AoC puzzle. :)
4
u/BaaBaaPinkSheep Dec 08 '21
Python 3
Using sets to solve part 2.
https://github.com/SnoozeySleepy/AdventofCode/blob/main/day8.py
4
u/sebastiannielsen Dec 09 '21
Improved my Perl solution to NOT require bruteforcing at all, instead it deduces each segment sequentially. Runs MUCH faster, produces an output in like 1 second.
https://pastebin.com/RprrLDr9
I finally got how I could calculate (without any guessing at all) each segment by first calculating the top segment, then getting which segments in the 1, then calculating the bottom left segment by using 6 (6 is the only 6-segment number that lacks one of the elements from 1). Then I could use that information to find 0, and then find the middle segment. After that, I could use 4 - only digit with 4 segments - to deduce the top left segment since I now had the 3 other.
Then I could find the last bottom segment by process of elimination. Then I loaded this into an array, and use a for loop, some regexp and a reverse hash list to convert the segments to actual digits.
4
u/DemiKoss Dec 09 '21
Rust ~285us.
Set-wise operations ended up being "very" inefficient, costing ~1.17ms originally. Swapping to bit vectors was the key.
4
u/theabbiee Dec 09 '21
Here's my good enough solution in Python
4
u/Solarmew Dec 09 '21 edited Dec 09 '21
Python 3
Yay! I'm So happy with my solution = ^.^ =
I based it on the fact that the total number of each segment in the 10 digits is always the same and is distinct for 3 of them. And from there it's easy to deduce the rest by elimination. Which is prolly what y'all did too :P But I still like it :)
Part 2
4
u/[deleted] Dec 09 '21 edited Dec 09 '21
Python Part 2
4
u/a_ormsby Dec 09 '21
Yay, a deduction-based puzzle! I would personally love to see more of that style, very fun. I admit I went off in a somewhat complex direction for a while, but when I realized I didn't actually have to map any of the wires to the segments, everything got so much more fun!
My Kotlin solution, supah fast!
4
u/ignurant Dec 09 '21 edited Dec 09 '21
Wow. I think I spent like 12 hours on this. I can't even remember the paths I've travelled, but each of them included "If you use bit masking, I bet there's a way you can just cycle through things and eliminate candidates and it eventually just cycles into place". Messing with bits is something I think can be very powerful, but I'm not great at thinking through. I definitely spent a fair amount of time over-planning for what my solution eventually became.
After spending an eternity trying to make a programatic solution, I started giving up and just went through with paper, detailing a specific solve order instead of hoping it could just fall into place. Given 1, 4, 7, 8, solve for 3 next, then 2 and 5, 6, 0, 9.
In the end, that actually looks kind of similar to a lot of other solutions, though they made it so much cleaner!
Ruby Pt. 1:
Ruby Pt. 2: Link for size
Edit: Some extra commentary notes:
Sets would have provided a much easier to understand api than bit masks, but I really wanted to bitmap. And using sets wouldnât have saved me that much time anyway.0h1000000...0b10000000,9, but found my assumptions wouldn't work. It turned out I was usingsortrather thansort_byin:This flipped my 2 and 5, which ruined me when comparing 5 to 6 but it took like 3 hours to work out what was going on.
4
u/mikkeman Dec 09 '21
I used Oracle SQL only, and it took way more time to get the algorithm than to write the queries.
here it is
4
u/joshbduncan Dec 10 '21
Python 3: Brute force approach.
4
u/-WorstWizard- Dec 14 '21
Rust Solution
Took a lot of logic to do this one, spent as much time just staring at the digits as I did programming.
3
u/dtinth Dec 08 '21
Array#permutationandString#trsaved the day for me. Part 2 takes about 30 seconds to run. I tripped up because of the line breaks in the example that was not present in the actual input. (The code is slightly cleaned up.)3
u/Breadfish64 Dec 08 '21 edited Dec 08 '21
C++
Very fun!
Mine is a non-brute force solution. I first find the patterns for the unique segment counts, then you can figure out the rest based on how the segments overlap with the ones you've found.
https://github.com/BreadFish64/AOC/blob/master/AOC/seven_segment_search.cpp
3
u/ShotgunToothpaste Dec 08 '21 edited Dec 09 '21
Took me a while to parse what the expected behaviour for part two was. That's what I get for skimming to try do part one faster.
Ended up drawing out some known/unknown numbers and then it became apparent that the 5/6 length numbers all had unique numbers of overlapping segments with the known values, so I didn't even need to figure out the letter-to-position mapping. Eventually settled on just using overlaps with 1 and 4.
C# / CSharp
EDIT: Figured out how to escape
#in a markdown heading3
u/HAEC_EST_SPARTA Dec 08 '21
Erlang
Solution on GitHub
Solved via process of elimination for each digit: I initially planned to determine the actual segment mappings, but it ended up being much simpler to determine each digit deductively using segment differences between the digits I had already figured out. The code feels a bit inelegant (rampant abuse of pattern matching ftw), but it gets the job done reasonably efficiently so ÂŊ_(ã)_/ÂŊ
0
u/[deleted] Dec 08 '21
[deleted] â view deleted comment
0
u/[deleted] Dec 08 '21
[deleted] â view deleted comment
3
u/autid Dec 08 '21 edited Dec 08 '21
FORTRAN
https://pastebin.com/ttPF63E6
Long boi. Lot of room for improvement in part 2.
edit: got it down to a size I'm comfortable posting
3
u/TcMaX Dec 08 '21 edited Jun 30 '23
Fuck spez
3
u/Archek Dec 08 '21
Golang + Prolog
Had to bust out the prolog today even though I was planning to it all in Go again this year. The problem is just too well suited for it :) I ended up calling a prolog program for each line, to have it figure out the digits by pattern matching. Still needs some optimising because the final program runs in 90secs for part2.
3
u/entoros Dec 08 '21
Q
Brute force solution to part 2.
3
u/Sykout09 Dec 08 '21 edited Dec 08 '21
Rust:
Part 1 is pretty easy, they basically gave you the solution, just check how many of the output value has a length of 2, 3, 4 or 7; correlating to the digit "1", "7", "4" and "8".
Part 2 is where the fun begins.
First observation is that there is a max number of characters (a to z) and the fact that the order does not matter. Thus we can store the entire of the signal/output value as a bit field into a u32, with every letter a different bit
Secondly, it is noted that "1", "4", "7" and "8" all have unique stroke count, but to map the rest:
With the combination of these two data, we can do a deduction on the assignment of the last 6 values by checking how many overlapping strokes it has with the number "1" and "4". This is extremely quick to check as we just do a bit-and operation and just count the ones.
Looking through how the segmented display is layout:
5 strokes:
6 strokes:
Once we followed through, we will get a list of 10 numbers with the corresponding bit patter. And we simply compare to the output to see which is the matching number, etc.
Bench:
Code Part 1 + 2
3
u/soylentgreenistasty Dec 08 '21
This was so fun! The coding is messy but the result is good :D PYTHON 3
3
u/giftpflanze Dec 08 '21
Factor
3
u/s3aker Dec 08 '21
Raku solution
3
u/Snoo_41044 Dec 08 '21 edited Dec 08 '21
Python
Part 1
Part 2
DFS + backtracking algorithm with OOP
3
u/ficklefawn Dec 08 '21 edited Dec 08 '21
Golang
With the condition that we know 1, 4, 7, 8 up front, I decided to use the following unique identifier for each number:
but using the minimal id each time, i.e. only calculate as far as I need. This gives me
and from there it's easy to learn the codes
3
u/wherrera10 Dec 08 '21 edited Dec 08 '21
Julia
Deductive.
3
u/Surye Dec 08 '21
Python 3
https://gist.github.com/Surye/2b6ab200e760c73c748b6c87746b653b
I normally would clean this up, but it's 1am, and I have work early. Basically I tried to just implement the logic I'd use on scratch paper to deduce any specific case.
3
u/raxomukus Dec 08 '21
Python3
On github
3
u/Ashyaa Dec 08 '21 edited Dec 08 '21
Python 3 solution for both parts:
Available on GitHub.
3
u/DeeBoFour20 Dec 08 '21
C
https://gist.github.com/weirddan455/1bd9222b938f2919ebb86ada4a1b9aac
Code is kind of ugly but it works. This is probably the one I struggled the most with.
I was just storing the data as strings but I decided to abandon that approach when I realized that string compares between the output "display" and the digits doesn't work (even though they contain the same characters, they can be in a different order).
Instead, I used some structs with an array of boolean values to represent the segments.
Code ended up being over 300 lines. I probably could clean up the code some but it took me a long time just to figure out the logic. I'm just waiting for some Python programmer to come along and solve this problem with a one-liner to embarrass me lol.
3
u/Osiris50 Dec 08 '21
python part 2
I used the number of times a light appeared as extra information to find which numbers it belonged to
paste
3
u/[deleted] Dec 08 '21 edited Dec 09 '21
Google Sheets
Part 1
A1:A200 = input
3
u/Brytnibee Dec 08 '21
An approach in Python!
3
u/flwyd Dec 08 '21
Raku, 9341 / 11194. Linked code derives segment properties from a list of digits; the original code for submission hard-coded segment-count-to-presence and segment-count-to-absence values, which was shorter but less elegant. Part 1 is a 1-liner after parsing:
[+] ($_<second>.grep(so *.chars == any(2,3,4,7)).elems for $.parsed.made)I lost about 40 minutes trying to figure out why my fancy input grammar wasn't parsing the input, and later learned that regexes in Raku treat
.as "any character including newline" and the default whitespace token consumes newlines (I knew the latter). This is great for parsing natural-language text and many programming languages, but very rarely AoC input. Updated my template to be more line-oriented.On part 2 I lost about half an hour before discovering that Raku sets iterate as a list of pairs (the
valueis alwaysTrue) rather than as a list of the elements you put into it. Even though I understand why it works like this I still feel it violates the principle of least surprise. Every other iterable set implementation I can think of works like a (possibly unordered) list with unique values, not exposing the internal "it's like a hash map with boolean values" implementation detail.3
u/RojerGS Dec 08 '21
My Python solution uses a couple of logical deduction rules I derived by hand, such as the obvious ones (digits 1, 4, 7, 8) and then things like the fact that 3 is the number that uses 5 segments and that contains the segments from 1.
Did anyone implement a full deductive system accepting a generic set of clues, of some sort? Reply to this comment if you did!
3
u/VictorTennekes Dec 08 '21 edited Dec 08 '21
Nim
Today took me a little longer, put a wrong index somewhere and took me a little to figure that out. Not the shortest or best solution probably but it works :) Any tips are always welcome!
3
u/surgi-o7 Dec 08 '21
ES6
https://github.com/surgi1/adventofcode/blob/main/2021/day8/script.js
3
u/mschaap Dec 08 '21 edited Dec 08 '21
Raku, see GitHub.
My logic for determining the segments of the digits:
3
u/Alligatronica Dec 08 '21 edited Dec 08 '21
JavaScript
Basically just solved it like a puzzle, initially I thought I'd be solving for segments, but segments don't really matter and it was easier to just use process of elimination to work out the characters
3
u/Zach_Attakk Dec 08 '21
Python
OK now I have to explain this mess...
The first part was easy. Check the length of the code, if it's in the list of lengths add one.
Pretty standard stuff, however I took the time to make my data structure nice because I had a feeling we would be solving all the digits.
That middle line sorts the wires in alphabetical order. At the time I figured the letters might be important, turns out it didn't really matter but this did help with some preparation later.
Part 2 is the reason I got zero work done today.
I built a function that identifies digits and puts them in a list in the index of the number they represent, so
_ordered[6]will be the wires for the number6I'm not going to put the code here because it's a massive mess.First pass I just grab the ones we know. 1, 4, 7 and 8. As I'm doing this, I store them as sets so I can do some difference calculation later.
On the second pass, I do stuff like checking how many segments overlap with numbers we already have. For example:
Working out that sort of thing took a while and it's a little hacky, but it worked flawlessly first try. I did have to sort the resulting strings again, because sets are unordered, to make sure when I later look for the index of a specific string, the strings actually match.
Part 1, Part 2, Notes.
3
u/axaxaxasmloe Dec 08 '21
J
Brute-forcing all
7!permutations. I'm new to the language, so this is probably not an idiomatic solution. Has been fun, though.3
u/encse Dec 08 '21 edited Dec 08 '21
C#
here is mine:
https://github.com/encse/adventofcode/blob/master/2021/Day08/Solution.cs
3
u/RoughMedicine Dec 08 '21
Python
It runs in 10ms. I saw cleaner solutions here, but I think set operations are a neat representation of this.
paste
3
u/RadioactiveHop Dec 08 '21
My python solution
Rather than directly working with digits, I first looked at the segments occurrences in the 10 patterns (digits 0..9):
Then segments a and c are 8 times on, but only c is in the 2-segments pattern (digit 1), same for d and g that are both 7 times on, but only d is in the 4-segments pattern (digit 4).
I then create a segment map (a python dict) that allows for decoding...
Probably far from optimal, but it worked
3
u/zonito Dec 08 '21
With detailed and graphical explanation: Python Solution
3
u/GiftOfDeath Dec 08 '21 edited Dec 08 '21
Way over engineered solution in GameMaker Language.
Part one was straight forward enough. Just count how many strings of certain length appear in the input.
In part 2 I went to the lengths of uh... Converting everything to numbers and comparing how many of matching 1 bits there are to find patterns. I reckon I could optimise this a little bit, might do later on.
Edit: Just when I was about to go to bed it dawned on me I could optimise this a lot rather than a bit. Have shaved the solve time for part 2 from about 60ms down to 8.5ms. :')
I was previously solving every number rather than just the relevant ones. That was a massive time saver, cut the run time down by about 75% (will still use that bit if I ever end up making a visualization of this). Secondly I was counting the bits very slowly, one by one, rather than masking. That halved the solve time again. I can sleep soundly tonight. :D
3
u/_luxcem Dec 08 '21
Python solution, mostly played with set intersections.
https://github.com/luxcem/advent-2021/blob/master/day08/main.py
3
u/nann1ck Dec 08 '21
Nice one this one...
It took me a while to see that the part 1 was straightforward.... So i used the decyphering strategy on part 1 as well...
if you start from 1 & 7 which have 2 common elements... you find 'a' and then it all unravels with some matching here and there...
Javascript : solution here
3
u/busdriverbuddha2 Dec 08 '21
Python 3
Got part 1 in one line:
Got part 2 in the ugliest code I've written in a while.
3
u/hrunt Dec 08 '21
Python 3
Code
What's a bull in a china shop look like? This code.
I worked my way through it methodically, step by step. The only tricky part was remembering that any segment with only a single candidate signal could not have that signal sent to any other segment.
3
u/chkas Dec 08 '21 edited Dec 10 '21
easylang
Solution (with visualization)
After trying to add more and more logical rules and thus making the program more and more complicated (I didn't get that each digit is present in each input line), I switched to the "simple" brute force strategy, which tries all possible connections (permutations) until all displays show a digit.
3
u/raevnos Dec 08 '21
Horrible hackish Java paste
3
u/timvisee Dec 08 '21 edited Dec 08 '21
Rust This one is fast!
Part 1 0.008ms (8Ξs)
Part 2 0.026ms (26Ξs)
day01 to day08 total: 0.757ms (757Ξs)
3
u/Edicara237 Dec 08 '21 edited Dec 08 '21
Full solution in Clojure:
paste
The basic idea for my solution to part 2 is to brute force: generate all different ways the displays might be broken (permutations of segments) and then to test if any of the resulting set of broken displays exist in the input.
While I got the idea to the solution early it took me some time to figure out the proper data structure for the problem. One hard to track bug was based on the wrong assumption that the set of signals is unique for each entry in the input.
3
u/TommiHPunkt Dec 08 '21
Matlab: I was shocked when this actually spit out the correct result the first time it ran through all the way. Zero consideration taken for nice code, I just wanted to get the task behind me. Not sure the headache I have is from reading the instructions or from something else.
Part 1 being a one liner after parsing is nice again.
How ugly can you make your conditionals:
Me: Yes.
3
u/phazy_x86 Dec 08 '21 edited Dec 08 '21
C
I counted the amount of occurences of each segment during the ten signal patterns:
You conclude from the figure that counting the amount of occurrences alone does not suffice to identify each segment. So what you need to do is to somehow identify each segment with a second value. I accomplished this by counting the occurrences in the digits that are identifiable solely by their length of segments. What I found was that the digits 4 suffices to distinct segment a from c and segment d from g:
With these two parameters, you can construct a lookup table for each input line and query against it, if the digit cannot be identified by its amount of segments alone.
Anyone interested in the implementation or in further documentation can go to my GitHub.
PS: For the Ctrl-F people : My code written in the C Programming Language can be compiled by both clang and gcc ;)
EDIT
In the original version, I used both digits 4 and 7 to generate lookup table. However, digit 4 suffices.
3
u/sanraith Dec 08 '21 edited Dec 08 '21
Typescript
day08.ts (github.com)
Instead of taking the digit characteristics into account, I went for a general solution. I generate a list of possible mappings for each segment, then eliminate the wrong mappings using backtrack.
3
u/something Dec 08 '21
Python one liner. This was the most fun to cram into one line
3
u/sdolotom Dec 08 '21
Haskell
Not sure if it's an optimal solution, but I liked the idea: I noticed that by finding those 4 simple digits from the first part, we can identify groups of wires
bdandegup to the order, i.e. we know which wires arebandd, but don't know which is which (same foreg). It's enough to identify all other digits by subset operations. For example, if a digit has 6 segments and has both ofbandd, but not both ofeandg, then it's 9, etc.Full code
3
u/Gravitar64 Dec 08 '21
Python 3, Part 1&2, 4ms
based on the fantastic idea of 4HbQ
3
u/kwenti Dec 08 '21 edited Dec 08 '21
Python
My solution in python.
The idea is that once the base digits 1, 4, 7 and 8 are identified, any digit is uniquely given by the 4-tuple of its "imprints" on those (ie the size of the intersection). For example, the imprint of 0 would be (2, 3, 3, 6). The {imprint -> digit} mapping can be computed from the known example correspondance.
Cheers,
Quentin
3
u/pistacchio Dec 08 '21
Brute-forced Typescript:
3
u/narrow_assignment Dec 08 '21 edited Dec 08 '21
AWK
Part 2:
3
u/thulyadalas Dec 08 '21
RUST
For part 2, there are multiple ways to deduct all digits. I'm not sure mine is the simplest or fastest but it works under 2ms. I cleaned some of the iterator stuff to a different function after I'm done (I'm not sure if closure parameters are better in trait methods yet).
3
u/Coffee_Doggo Dec 08 '21
Rust [code] [explanation]
I'm striving to get very fast runtimes, so here's my solution which runs in 0.2ms. Then, I read part 2 again and I realized that I'm fucking stupid, because I went through it so fast I didn't realize it already gives you the mapping between letters and segments. My solution resolves them individually for every line.
3
u/armeniwn Dec 08 '21 edited Dec 08 '21
Yet another Python3 script, although there are some languages much better fit for this challenge, but still, python has sets. You can do set operations with sets, like "intersection", which is what I'm basically doing here: