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
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.
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.
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 -l5
u/RodericTheRed Dec 08 '21 edited Dec 08 '21
Python3
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/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/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/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
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:
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/raxomukus Dec 08 '21
Python3
On github
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/RiemannIntegirl Dec 08 '21 edited Dec 09 '21
Python 3.9
Edit: Formatting on the Relabel display segments didn't display, so I wrote it out.
The idea for part 2 is as follows:
Relabel the display segments as: top=t, top left =u, top right=v, middle=w, bottom left = x, bottom right =y, bottom=z
For each line in the input file: Make a dictionary with key=number of segments, value=list of strings with that length By process of elimination map each of t,u,v,w,x,y,z to exactly one of a,b,c,d,e,f,g Use this mapping to figure out what the display is showing and add it to our total.
Part 1
Part 2
3
u/rtm0 Dec 09 '21 edited Dec 09 '21
R
What if there was a unique signature for each digit which didn't change when you scramble the segments or when you scramble the order of the digits? Then you could match the signature of each digit to the unscrambled signatures and, viola, you have the mapping to identify digits straight away.
What properties are invariant under scrambling segments? Well the intersection patterns of the digit segments are basically the same. The particular of segments in the intersections will change, but the sizes of those intersections will not. This is the basis for the signature pattern of a digit.
As an example: 4 is given by bcdf. The segment intersections with other digits are 0 -> bcf, 1 -> cf, 2 -> cd, 3 -> cdf, 4 -> bcdf, 5 -> bdf, 6 -> bdf, 7 -> cf, 8 -> bcdf, 9 -> bcdf. So the signature lengths are ( 3 2 2 3 4 3 2 4 4 ) since "bcf" has length 3, "cf" has length 2, etc. We record the signature lengths in sorted order so that the signature is invariant under permuting the order of the digits. The final calculated signature for 4 is ( 2 2 2 3 3 3 3 4 4 4 ). It turns out the signature for each digit 0-9 is unique.
https://github.com/mccorvie/advent-of-code-2021/blob/main/Dec%2008b.R
3
u/GaloisGirl2 Dec 14 '21 edited Dec 16 '21
COBOL
2
u/kupuguy Dec 08 '21 edited Dec 08 '21
My day 8 Python solution is a bit long to paste in here easily: https://github.com/kupuguy/aoc2021/blob/main/src/day8.py
Also I have a Jupyter Notebook with the puzzle and solution to make it easier to read: https://github.com/kupuguy/aoc2021/blob/main/day8.ipynb
Basically I extracted the easy digits then did a bunch of set intersections to find the others. Finally I ended up with a dict from digit to set of segments.
2
u/zonito Dec 08 '21 edited Dec 08 '21
With detailed and graphical explanation: https://zonito.medium.com/seven-segment-search-day-8-advent-of-code-2021-21e5bc965005
Python
2
u/ultra_mind Dec 08 '21 edited Dec 09 '21
JavaScript
https://github.com/TheAngularGuy/aoc2021/tree/master/day8
2
u/[deleted] Dec 08 '21 edited Dec 09 '21
Python 3
I can't tell if I'm clever or dumb at this point.
I had some vague memories about seven segment displays and BCD from uni. There is undoubtedly a smarter way to use this information, but I came up with finding the amount of set bits from ANDing known numbers with unknowns using the provided solved input.
paste
2
u/LaybeRize Dec 08 '21
Java
My first attempt was puzzling the letters to their correct place and that worked fine, but was really not efficient both time and code wise.
So when I finished I looked trough some other code and found people mapping the clear identifiable numbers 1,4,7,8 to the inputs. So I tried to replicate that and found out, that with only the knowledge about the 1 and 4 you can find out any number from 0 to 9.
The algorithm sorts like this:
And the code for both parts looks like this:
2
u/Yelov Dec 08 '21 edited Dec 09 '21
Python [part 2]:
GitHub link
It's a bit slow, takes 5 seconds for me. The one-liners are harder to read.
This is my first solution for part 2, it runs instantly but it's ugly af - GitHub solution.
2
u/[deleted] Dec 08 '21 edited Dec 09 '21
Python3
Absolutely ugly answer with explanation :
paste here
2
u/fetshme Dec 08 '21 edited Dec 09 '21
Haskell
2
u/domm_plix Dec 08 '21
Perl
Solved first with the best dev tool available: pen & paper.
Converting my scribblings to code took more lines then necessary, and I even used a CPAN module for the set comparison.
Here is what I used to get my second star:
https://github.com/domm/advent_of_code/blob/f2fd3d9fcec27bec193bb13303a7c8d09b99ede7/2021/08_2.pl
I might clean it up a bit more later...
2
u/tcbrindle Dec 08 '21 edited Dec 08 '21
C++
That was a tough one! I had to sit down and puzzle it out on a piece of paper, and then coded up my solution as basically a direct translation of the "algorithm" I'd just come up with. It's not exactly pretty.
Runtime is ~140µs for part 2, so it's not the fastest either but hey, it works...
Github
2
u/Data-scientist-101 Dec 08 '21 edited Dec 08 '21
Python solution. Computation time (excluding data load) was 0.015 seconds on my laptop computer. Looking through the reddit board, looks like it is similar to others but I used regex instead to find elements. I also found the set.different instead of set.intersect (not that that is all that groundbreaking). Just sharing the solution.
Any ideas to further speed things up?
I've got a Wiring Problem
(HOpefully this is formatted right for old.reddit. I tried following the steps. If not, paste in the comments what I might have done wrong? Clicked markdown, and then put things 4 spaces in.
*Note you may find it weird to include an instance reference inside my class definition. I was too lazy to take those out. I use that approach when debugging my classes and then at the end change them all to self instead.
2
u/Sheler_ Dec 08 '21
Desmos
I'm not sure whether it belongs here since "programming" in Desmos is a bit... unconventional. But mods told me to consider posting here, so here goes:
P1: https://www.desmos.com/calculator/o7uik5ichx
P2: https://www.desmos.com/calculator/xrzd5dvqa3
Technical note: since Desmos can't parse input, or even work with strings, I used python to parse it into the Desmos list, interpreting words as numbers in Base36
2
u/evamicur Dec 09 '21 edited Dec 09 '21
first pass at part 2 I did the same as much of these with first solving the 4 unique by length, then some custom heuristics to solve for the length 5&6 based on their set relations to other known digits. I tried to rewrite and make something a bit less ad hoc. I landed on something that takes a "reference" (in this case the original digits set) and uses length and sub/superset relations to the other digits to create a unique mapping (tuple of outputs of each function) to each digit. Then the inputs can be treated the same way and you can get the original numbers by comparing the tuple of function outputs on input/reference to get the mapping and apply to the output. Sorry bad at explaining maybe the code makes more sense
Python 3.9.5
edit: cant get formatting here's GitHub link https://github.com/ecurtin2/advent-of-code/blob/main/year2021/d8.py
edit: posting guidelines
2
u/foolnotion Dec 09 '21 edited Dec 09 '21
C++ solution
I did not implement any rules, I used a search with some constraint satisfaction check. the goal was to find a mapping that unscrambles the segments. With some optimizations it runs in ~1ms on my PC. The main insight is that for each letter group size, we know the possible digits, and we can determine whether or not any given segment will be active in any of those digits. This is useful to filter out combinations that are not legal. Furthermore I use a validation check to determine whether the found mapping can successfully decode the output digits. If yes, the number is returned.
github solution
2
u/dkhundley Dec 12 '21
Holy wowzers, Part 2 was something else! Setting the code aside, it was a bit of a challenge just to figure out how to logically deduce how to derive the numbers. It's not pretty, but I did it and got the right answer!
https://github.com/dkhundley/advent-of-code-2021/blob/main/day-8/seven-segment-search.ipynb
2
u/x3mcj Dec 23 '21 edited Dec 23 '21
Took way more to understand than what Im willing to accept
Python
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:
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/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:
3
u/jf928ngl60g1 Dec 08 '21 edited Dec 08 '21
TypeScript
https://github.com/adrbin/aoc-typescript/blob/main/2021/8/puzzle.ts
I have to say I'm not a fan of the today puzzle. The puzzle description felt really convoluted to me and took me literally 1 hour to decode pondering about the relation between signals and the output values where there was actually none and finally realizing that part 1 is actually as trivial as Day 1.
For part 2, I tried first to tinker with Set operations but in the end I just used permutations to check all possible display segment mappings. Is it just me or it felt like a steep difficulty increase from the previous days (part 2)?
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
2
u/usesbiggerwords Dec 08 '21 edited Dec 09 '21
Python 3. At first I tried to work out the pinouts for the display AND the encoding for the digits. Once I realized that wasn't needed, this went better. Not pretty, but functional.
https://pastebin.com/Vb2Y2FYZ
Edit fixed link
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/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/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/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/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/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...
4
u/InflationAaron Dec 08 '21
Rust
A bit of set operations
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 analysisaimless 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):
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.
1
u/[deleted] Dec 08 '21 edited Dec 09 '21
Python
This is the interesting point - figuring out the mapping. Basically count the frequency each letter appears and deduce the segment based on the frequency that it lights up. From the mapping, trivial to determine the digit and reading.
1
u/RJdaMoD Dec 08 '21
Mathematica
Part 1:
Part 2:
1
u/[deleted] Dec 08 '21 edited Dec 08 '21
Part 1 Kakoune keystrokes. Probably could be golfed. Result is an ammount of selections.
Shorter, destructive version:
1
u/KamcaHorvat Dec 08 '21
Finally somewhat interesting puzzle. Solution in Kotlin.
}
1
u/GoldenBears Dec 08 '21 edited Dec 09 '21
Python
Pretty brute force once again: paste
1
u/uglyasablasphemy Dec 08 '21
My 🐍️ solution
The gist of it is:
Make all the possible displays:
1
u/minty_mule Dec 08 '21 edited Dec 08 '21
Generic pure-logic Kotlin solution, works with any non-conflicting configuration of digits :)
1
u/AOC_2020 Dec 08 '21 edited Dec 08 '21
// KOTLIN
1
u/cggoebel Dec 08 '21 edited Dec 09 '21
Raku
Part One:
1
u/theabbiee Dec 08 '21 edited Dec 09 '21
WARNING: Really Ugly Code
Language: Python
Here
Here's the code after refactoring, looks much better now,
Here
1
u/Justinsaccount Dec 08 '21 edited Dec 09 '21
[Python]
So for part 2 you can solve it efficiently enough (500ms) by just brute forcing all 5040 permutations using:
(some functions not shown :))
I've scrolled through a bit but have not seen the generic efficient approach done, which is to work out the possible candidates for each segment, then narrow down the search space using that:
What that does is first build the candidate info that looks like this:
In the first iteration it will recurse with two candidate maps that cover the two cases for the '1' digit,
and
The neat thing is that after adding entries to the map for 'f' and 'c', it will automatically assign 'a' to the remaining letter out of 'edb', BUT without needing any special casing. Each candidate added to the mapping reduces the possibilities for the next level.
1
u/TheOx1 Dec 08 '21 edited Dec 09 '21
Python
Pretty straightforward solution just inferring what letter corresponds to every segment by means of subtracting or intersecting between known and unknown digits. Enjoying seeing your solutions guys :)
Code
1
u/mar1u50 Dec 08 '21
Kotlin:
1
u/esolitos Dec 08 '21 edited Dec 09 '21
I saw some quite smart solutions down here, mine is special.. Just some deductions based on shapes. :)
The interesting part follows, the full code is here on GitHub
1
u/goeyj Dec 08 '21 edited Feb 27 '26
[JavaScript]
Originally solved and submitted with a solution that brute forced the permutations, but rewrote to generate the correct permutation rather than generating and cycling through all of them. The code is a little uglier, but it went from 3s to about 30ms runtime.
1
u/Ruais Dec 09 '21 edited Dec 10 '21
i realise i went about solving this one in probably one of the most boring ways, but it's what jumped at me
Python for this one
by counting how many times each line segment appears in the numbers 0 through 9, you can determine which line segments are e, b, f
you can use e, b, f to find which numbers are 0, 6, 8
line segments a, c are confused, and so are d, g; only a, g appear in all 0, 6, 8
you now know which line segment is which, and can decode to get the correct digits
1
u/Mpeterwhistler83 Dec 09 '21
def part1(): with open('inputs/day8a') as file: data = [x.split('|')[1].strip().split(' ') for x in file.readlines()]
def part2():
1
u/frerich Dec 09 '21
Elixir
I think I might have found an interesting solution to part 2: I built one big list comprehension which gradually weeds out plausible wire-to-segment combinations:
It first draws two values
candffrom the setabcdefgsuch that there's a pattern in the input with those two letters. It then draws another value and checks for a three-letter pattern, and so on. By incrementally drawing characters and checking for implausible assignments early on, I can greatly reduce the search space. This runs in 20ms on my laptop.1
u/s3nate Dec 11 '21 edited Dec 13 '21
C++
part 1: linear scan on output values to count occurences of "easy" numbers using a hashmap
part 2: brute force using a contains(s, t) function to test for the existence of segments s in segments t
-> also sort signal patterns by size descending to reason top-down by process of elimination
-> and also sort output values in alphabetical order to normalize hashtable look-ups when decoding output values
solutions: source
1
u/RepresentativePen629 Dec 14 '21
I've decided to go for universal solution. The core loop is
for perm in ['a', 'b', 'c', 'd', 'e', 'f', 'g'].iter().permutations(7) {let perm : Vec<char> = perm.into_iter().cloned().collect();let values : HashSet<u8> = wires.iter().map(|w| encode(w, &perm[..])).collect();if values == canonical_values {return perm}}Code (Rust)
1
u/Innis_Gunn Dec 20 '21
Node JS solution: https://github.com/etnichols/advent-of-code/blob/master/day8/solution.mjs
1
u/arthurno1 Dec 26 '21 edited Dec 29 '21
Emacs Lisp
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/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 ¯_(ツ)_/¯
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/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.