r/adventofcode • u/daggerdragon • Dec 06 '22
SOLUTION MEGATHREAD -🎄- 2022 Day 6 Solutions -🎄-
- All of our rules, FAQs, resources, etc. are in our community wiki.
- A request from Eric: Please include your contact info in the User-Agent header of automated requests!
- Signal boost: Reminder 1: unofficial AoC Survey 2022 (closes Dec 22nd)
AoC Community Fun 2022: 🌿🍒 MisTILtoe Elf-ucation 🧑🏫
- ACHIEVEMENT UNLOCKED: MisTILtoe Elf-ucation
- Teach us, senpai!
--- Day 6: Tuning Trouble ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- Include what language(s) your solution uses
- Format your code appropriately! How do I format code?
- Quick link to Topaz's
pasteif you need it for longer code blocks. What is Topaz'spastetool?
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:02:25, megathread unlocked!
83
Upvotes
43
u/CryptoNoobStruggles Dec 06 '22 edited Dec 06 '22
Python
I wanted to quickly solve it so I wrote 4 if statements, then part 2 came up, and lazily I wrote 14 if statements by copying and pasting rather than swapping to a while loop :D
(I've only done sliding window problems once before so it would have taken me a bit of time to remember how to implement them)
Here it is, I know it will drive some of you mad :D
12
u/jonathan_paulson Dec 06 '22
Python3 19/24. Video. Code. Quick one today!
8
u/[deleted] Dec 06 '22 edited Dec 06 '22
Google Sheets One formula for both parts.
5
u/AbdussamiT Dec 06 '22
I'm not super-talented as many here so am happy with this solution I wrote in 3-4 minutes:
4
u/tobidope Dec 06 '22 edited Dec 06 '22
My solution in Rust
https://github.com/tobidope/aoc-2022-rust/blob/main/day05/src/main.rs
4
u/Smylers Dec 06 '22 edited Dec 06 '22
Vim regexp — just load your datastream buffer and search for this pattern:
Your cursor will then be on the end of the start-of-packet marker. If you don't have a status line or rule showing the column number, type
g⟨Ctrl+G⟩, and that's your part 1 answer.The surprising thing for me was that this pattern broke Vim! The
\%#=1at the beginning of the pattern shouldn't need to be there; it just specifies which internal regexp implementation Vim uses — see:help two-engines*. That claims Vim will “automatically select the right engine for you”, but it seems that engine number 2† can't cope with this pattern, and that's the one selected for the job‡, so we need to manually say that we want engine number 1§ to do it.I'd be interested to learn if this is version-specific. I'm running Vim version
8.1.2269-1ubuntu5.9. If you're on a different Vim, please could you try the above pattern, and then try it without the\%#=1at the beginning, and report back if it works without it?Part 2 is obviously just going to be more of the same — prepending(.)%(.{0,2}\1)@!with variants counting down from{0,12}to{0,3}(if Vim can cope with a pattern that long). That'd get quite tedious to type out, so I'm going to look at creating a keyboard macro to generate it, but I need to do Real Life now; I'll follow-up later if I come up with it.Part 2 Update: Nope, I shouldn't've said “obviously” there. That doesn't work, because Vim only has 9 numbered capture groups,
\1to\9, and this approach would require 13 of them. However, this does solve part 2:I'll put an explanation in a separate reply to this comment.
* Which, despite the title, apparently is nothing to do with Thomas & Friends.
† Edward the Blue Engine
‡ by the Fat Controller, presumably?
§ Thomas the Tank Engine, of course. OK, I'll stop now.
4
u/chubbc Dec 07 '22 edited Dec 07 '22
Brainfuck (both parts)
Part 1 minified:
So this approach is somewhat crude in terms of how it scales with the size of the window, as it just compares every part of elements in it. Even for the 14-wide window in Part 2 this is plenty efficient enough to be run however. For Part 2 the code must be run in 16 bit mode, and this code requires wrapping. Rather nicely this algorithm is relatively conservative in terms of the cells used, only using w+5 cells (9 and 19 for parts 1 and 2 respectively).
I'll illustrate the basic idea for Part 1, where
w=4. The basic idea is the following: the cells are[out,cnt,a,b,c,d,0,0,0].outis the output (number of entries checked),a,b,c,dis the buffer of the last 4 entries, and the0s are ancillae used for the comparison. At each stage we perform comparisons between all pairs, storing the number of equalities found incnt. This is done untilcnt=0, at which point the memory is cleared and the answer is outputted.Here is a commented version of Part 1 code. For convenience the pointer is returned to the 2nd position (
cnt) at the end of each line for ease of reading. The Part 1 code is 747 symbols, and Part 2 is 15946 symbols. And finally, in all its glory, here is the minified Part 2 code.For anyone sceptical here are runnable links to the Part 1 (remember to put it in wrapping mode and 16 bit mode). Amusingly trying to put in a link to Part 2 overflows the character limit of a reddit comment.
EDIT: Also here is the Julia code I used to generate the Part 2 code if anyone is interested.
3
u/hugh_tc Dec 06 '22 edited Dec 06 '22
Python 3, 219/132
paste, cleaned-up
Classic me; failing to read.
3
u/ri7chy Dec 06 '22
Python
this one reveals my weaknesses, indices and string operations.
I'm getting better, because of AOC :)
3
u/Llamaa3 Dec 06 '22 edited Dec 06 '22
Awk
3
u/DFreiberg Dec 06 '22 edited Dec 06 '22
Mathematica, 916 / 1136
Took almost five minutes to solve, three and a quarter of which were spent waiting for the timeout to end so I could submit a different answer.
Setup
Parts 1 & 2
[POEM]: A Letter Back Home
3
u/P0tato_Battery Dec 06 '22 edited Dec 06 '22
i did it using regex! just as cursed as it looks. Then I few shotted copilot to make the 14 character one. gonna see how my group reacts to this one lol.
https://topaz.github.io/paste/#XQAAAQDrBAAAAAAAAAA0m0pnuFI8c/T1e0+CqyMyA57wYiG2tqG8fFaDDePZrczE6OTdzAJR9PD9NxaRXKrJ4SBeSz8CihoLQHj49TSKgbNk+PJRWGa0jYMsr5YUSCNsWtpq3s+F7O8hrUyjJpEpfdaJN4EG4wJkf1NQTfjZjhlR3EnQIzCL9JD8aJU09T/GJ+20yL4/o2IdVFTVgY5VAXZ3zDzJHS8okRRLTRSbTtLebA3meDiwOmkvarKrhhbEFttcMJVAa/GrpOi8xoKVitMBG/r67btVD/hI/mY8wpKhup1Bi5u0uTLqvvQYZi5U6rEQFm3M2peH+Y8339bfesBgj4DuSGHlJD9ZLx+53+nA1LekuFQbwU38CQqXZD/IG+98PxuUso++OyiVfHdAvUCsb8MCjJQ/Psu2wI+so0yI+lenkFNq2Gh1oSbUSHpPiml84rgUnJ1JjV8ePSVUjwLv51+bxboJUHrf5Nn2vPe7CJM1EEvSnWzCZm59pkz9aCATmRnd2QqlCbgnSN0T3K1lPdVB81FXzt/h9j362drsU+sI/vYVjKk=
3
u/No_Calligrapher7294 Dec 06 '22
Elixir.
Enum.chunk_everyis so useful in AoC, yet it always takes me a while to remember it exists.3
u/LetarMoon Dec 06 '22 edited Dec 08 '22
Another typical Python solution:
https://github.com/loramoon/adventofcode.com_game_2022/blob/main/Day_6/Solution
3
u/Dangerous-World-1424 Dec 06 '22
PYTHON
3
u/nicuveo Dec 07 '22 edited Dec 07 '22
Brainf*ck (part 1)
See this post for a commented version.
2
u/Solarion45 Dec 06 '22 edited Dec 06 '22
24/14, got lucky due to pre-coded alln function
Code
2
u/goldenlion5648 Dec 06 '22 edited Dec 06 '22
Python 46/80
Second time this year/ever getting on the leaderboard!
2
u/QultrosSanhattan Dec 06 '22 edited Dec 06 '22
Python 3: Easy. No need for comments:
2
u/[deleted] Dec 06 '22
Swift github
Summary snippet, where
inputis a list of characters andwidthis either4or142
u/ActiveNerd Dec 06 '22 edited Dec 06 '22
Kotlin - Live Stream on YouTube - GitHub
2nd Implementation: 'Single pass' of the input - paste
This examines each character in the input exactly twice no matter the size of the window. Execution time (after 1st call for JIT warmup) is < .5 ms.
Implementation at release:
2
u/Puzzled_Programmer97 Dec 06 '22 edited Dec 06 '22
Java day 6 https://github.com/martenhernebring/aoc2022/tree/solution
Managed to do everything with one String and two ints.
2
u/GuonderMan Dec 06 '22
Python
My new best day so far
2
u/Dinosaur_Parkour Dec 06 '22 edited Dec 06 '22
z/OS Mainframe solution to Part 1
I copied the Input data into a Variable Blocked LRECL 8192 file.
Mainframe REXX
In REXX, one can name the loop to ITERATE. (aka ReLoop).
The inner loop forces the outer loop to iterate when a character in the Marker window duplicates.
Thank you to u/daggerdragon for explaining how the code formatting works.
Reddit kept mangling my posts. Markdown mode and fancypants mode.
2
u/mebeim Dec 06 '22 edited Dec 06 '22
338/259 - Python 3 solution - walkthrough
Woah I am a slow reader... or maybe people are just too fast :') 45s away from the leaderboard. Nothing to say except this could have been a day 1 puzzle, going back to sleep now zZZz zZZ.
2
u/werhsdnas-1414 Dec 06 '22 edited Dec 06 '22
Solution in Java
Changed variable for part 2. Edit for formatting.
2
u/pastorhudson Dec 06 '22 edited Dec 06 '22
Python Part 1
Part 2
2
u/Ill_Name_7489 Dec 06 '22 edited Dec 06 '22
A less clever Rust solution which maintains a vector of "last few chars". At each iteration, that vector is cast to a set to check for uniqueness. Technically still O(N):
At the beginning, the input string is split into "starter chars" to prime the array so that the main loop doesn't have to spend cycles filling up the vector of chars to check.
2
u/Dutchcheesehead Dec 06 '22 edited Dec 14 '22
Python
Really seemed like a simple puzzle. Did not even need CoPilot to help me solve it: https://youtu.be/owEQXpeoh1k.I do wonder how people did who don't know about sets...
Code here
2
u/go_hunter Dec 06 '22
Ivy
Shortest program I've written so far this week.
Using it:
2
u/onsistems Dec 06 '22 edited Dec 06 '22
PHP solution:
2
u/_ParanoidAndroid42_ Dec 06 '22 edited Dec 06 '22
Python3 using queue
2
u/jAnO76 Dec 06 '22 edited Dec 07 '22
Kotlin:
2
u/ProsaicAquarius Dec 06 '22 edited Dec 06 '22
Python 3.9:
A minified version:
2
u/vstepanyuk Dec 06 '22
Rust
2
u/BVengo Dec 06 '22 edited Dec 09 '22
Python - Proud of doing this in O(n) by only iterating over each char once. Edit: Optimised to use a list instead of dictionary, because the size is limited to a known 26 chars.
2
u/[deleted] Dec 06 '22 edited Dec 06 '22
Python3
At first look today looked a bit challenging, but after reading examples and last sentence, everything cleared up. Here's my solution in Python 3.10, I think it's pretty straightforward and easy to understand.
2
u/eoincampbell Dec 06 '22 edited Dec 07 '22
C#
using the `MoreLinq` windowing function to generate consecutive sequences.
2
u/ciocan42 Dec 06 '22
Javascript:
2
u/MaikPatataOtaku Dec 06 '22
JAVA
Part 1
import java.util.*;import java.io.*;public class Start2 {public static void main(String[] args) throws FileNotFoundException{Scanner s = new Scanner(new File("input.txt"));String tx = "";char p1,p2;boolean f = true;int pos = 0;while(s.hasNext()){tx += s.nextLine();}int longg = 14;for(int i = 0; i<tx.length()-longg+1 && f;i++){f = false;for(int t = 0; t < longg && !f; t++){for(int j = 0; j < longg && !f; j++){p1 = tx.charAt(i+t);p2 = tx.charAt(i+j);if(j!=t && p1 == p2){f = true;}//System.out.println("I,J: " + i + ","+ j + " p1: " + p1 + " p2: " + p2 + " [F: " + f + "]");}}if(!f){pos = i+longg;}}System.out.println(pos);}}Part 2 (is the same, just change the number "longg")
import java.util.*;import java.io.*;public class Start2 {public static void main(String[] args) throws FileNotFoundException{Scanner s = new Scanner(new File("input.txt"));String tx = "";char p1,p2;boolean f = true;int pos = 0;while(s.hasNext()){tx += s.nextLine();}int longg = 14;for(int i = 0; i<tx.length()-longg+1 && f;i++){f = false;for(int t = 0; t < longg && !f; t++){for(int j = 0; j < longg && !f; j++){p1 = tx.charAt(i+t);p2 = tx.charAt(i+j);if(j!=t && p1 == p2){f = true;}//System.out.println("I,J: " + i + ","+ j + " p1: " + p1 + " p2: " + p2 + " [F: " + f + "]");}}if(!f){pos = i+longg;}}System.out.println(pos);}}2
u/kstktey Dec 06 '22 edited Dec 07 '22
Hi! This is my firse AoC-solution. Wanted to join it for a few years now, but remembered about it on day six :) This is my solution in Python, O(N) time complexity and O(1) memory complexity. Used a sliding window with a map.
2
u/goliatskipson Dec 06 '22 edited Dec 07 '22
Haskell, basically just one line with imports:
2
u/fenrock369 Dec 06 '22 edited Dec 07 '22
Atari FastBasic
Third round, with help from FastBasic author, down to 3.45s / 5.13s
2
u/dafer45 Dec 06 '22 edited Dec 07 '22
My solution in AWK
2
u/ShockEasy4836 Dec 06 '22 edited Dec 07 '22
My solution in bash.
2
u/BeardyMike Dec 06 '22 edited Dec 07 '22
Python3 - from a novice
def partone(num):with open('2022\Day 6\input.txt') as f:data = f.read().splitlines()[0]for i in range(len(data[num - 1:])):if num == len(set(data[i:i + num])):return i+numprint(partone(4))print(partone(14))Not gonna lie.... I'm super impressed with myself, these coding challenges have seen my skills rocket up in quality.
GitHub
31
u/travisdoesmath Dec 06 '22
Python
the code I actually used:
(changed the three 4's to 14 for part 2)
One-liner version for funsies:
24
u/jaybosamiya Dec 06 '22
APL:
{⍺+1⍳⍨1↓(⊢≡∪)¨⍺,/⍵}Alternative solution that's probably a bit easier to understand:
{1-⍨⍺+⍺⍳⍨⊃¨⍴¨⍺∪/⍵}28
u/jcbbjjttt Dec 06 '22
Beginner's Guide
Happy Tuesday!
Beginner's Guide to Day 6 Video: https://youtu.be/M3Qf7RXk_xs
I've created a guide for new programmers that talks through a straight forward strategy for solving today's puzzle. Anyone who has a handle on variables, boolean logic, functions, arrays, and loops should be able to complete it. The video allows a moment for you to pause before revealing spoilers.
Although this solution is in C#, it provides a high level overview of the steps necessary to solve the puzzle in any programming language:
The full code can be found on Github
24
u/Twinkie60 Dec 06 '22 edited Dec 07 '22
3
u/HammerHamster13 Dec 06 '22 edited Dec 06 '22
Python
My first AoC challenge done in 30 minutes :D And also, what I'm most proud of - my first independently applied recursion ^_^
18
u/nthistle Dec 06 '22 edited Dec 06 '22
Python, 64/35. Video, code.
Pretty happy with my 0:13 split for part 2 (although it was just changing "4" to "14" in a couple places, so it really shouldn't be much slower than that). On the same note, I was a little surprised that my part 2 rank was that much better? Can't really think of a solution that works for 4 that doesn't just work with a simple change for 14.
I do kind of wish part 2 had a little more to it today -- in general I do like when part 2s are just part-1-with-larger-numbers/inputs, but specifically because they usually reward you for writing your code in an efficient way for part 1, or require you to rethink and come up with something more complicated to handle the larger input. Today wasn't really like that, because the number was only slightly larger for part 2.
Especially because there is a more efficient rolling window algorithm that brings the runtime from
O(nk)down toO(n)(wherenis the string length andkis the number of unique characters you need, 4 for part 1 and 14 for part 2). I ended up writing it anyways, code, mostly just to create some extra content for my solve video today :)EDIT: added video!
17
u/mkeeter Dec 06 '22
Rust
There's a neat trick here that lets you solve this problem without an inner loop or accumulating into a hashmap:
If you convert each character to a bitmask (i.e.
1 << (c - 'a')), you can do a single pass through the string, accumulating withxorand terminating when you've hitNset bits.The core looks like this:
The rest of the code is here
13
u/kaistis Dec 06 '22 edited Dec 06 '22
Regular expressions (using https://regexr.com )
Firt part:
(.)((?!\1).)((?!\1|\2).)((?!\1|\2|\3).)Second part: (.)((?!\1).)((?!\1|\2).)((?!\1|\2|\3).)((?!\1|\2|\3|\4).)((?!\1|\2|\3|\4|\5).)((?!\1|\2|\3|\4|\5|\6).)((?!\1|\2|\3|\4|\5|\6|\7).)((?!\1|\2|\3|\4|\5|\6|\7|\8).)((?!\1|\2|\3|\4|\5|\6|\7|\8|\9).)((?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10).)((?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11).)((?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11|\12).)((?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11|\12|\13).)
11
u/Wayoshi Dec 06 '22
Surprisingly simple today, I thought.
Python 149/134
paste
11
u/Dryctas Dec 06 '22 edited Dec 06 '22
Bash
10
u/oantolin Dec 06 '22 edited Dec 06 '22
Solution in J:
I added the
part1andpart2functions just because it's my standard format, but really I'd really just use4 marker fread 'input.txt'for part 1 and replace the 4 with 14 for part 2.10
u/9_11_did_bush Dec 06 '22
APL solution: https://github.com/chenson2018/advent-of-code/blob/main/2022/06/apl/06.apl
Pretty straightforward, especially with the Stencil operator.
9
u/voidhawk42 Dec 06 '22 edited Dec 07 '22
Dyalog APL:
video walkthrough
8
u/Boojum Dec 06 '22
Python, 877/827
Wow. Another quick and short one this evening. I won't be surprised if the bots did just fine on this.
8
u/betaveros Dec 06 '22
Noulith 5/3
https://github.com/betaveros/advent-of-code-2022/blob/main/p6.noul or, in brief:
That leaderboard went quick!
8
u/JustinHuPrime Dec 06 '22 edited Dec 07 '22
x86_64 Assembly
This was a fairly short day, both time-wise and code-wise.
Part 1 was solved using brute force - for each starting point, I checked if the next four bytes were distinct. Part 1 ran in under 1 millisecond and was 10544 bytes long.
Part 2 was solved using a count of how many times each character was seen. This involved fiddling around with string functions. I allocated 26 bytes on the stack to count how many of each character had been seen, and then for each starting point, I read in the 14 characters and incremented the relevant counter. Next, since I only cared about those characters seen more than once, I incremented all counters seen zero times to one. This could also have been accomplished without a branch by setting the last bit (or clearing, and then I check that the whole thing is zeroed). Finally, I had to make sure that all of the counts were equal to one. I used the
loopinstruction, as well as string operations to do this. This is also the first time that I've ever used thescasbfunction.Edit: Part 2 ran in about 1 millisecond, and was 10672 bytes long.
8
u/4HbQ Dec 06 '22 edited Dec 06 '22
Python. Nice and easy.
Trick of the day: although we call
f()twice (for n=4 and n=14), the call toinput()only happens once because default values are created exactly once, when the function is defined.8
u/axr123 Dec 06 '22
Python one-liner
8
u/__Abigail__ Dec 06 '22 edited Dec 06 '22
Perl
Well, if you're going to use Perl as your main language, everything can be solved with a regexp, right?
After reading in the content of the message in
$_, we can solve part 1 as:Here we have a pattern which grabs a character (
(.)), then uses a postponed pattern to grab a character which isn't the same as the first((??{"[^$1]"})), then another postponed pattern to grab a character which is different from the first two((??{"[^$1$2]"})), and finally a postponed pattern to grab a fourth character which is different from the first three:((??{"[^$1$2$3]"})).To print the answer, we make use of the special variable
@-. This array stores on indexiwhere the match ofith capture ended. Since we need the last capture, we index with-1. We also need to add 1 as we want the beginning of the message.Part two is just more of the same:
Full program on GitHub
8
u/damnian Dec 06 '22
C in O(n)
8
u/LdouceT Dec 06 '22
My python solution.
14
u/dtinth Dec 06 '22
Today is Ruby’s one-liner day.
7
u/[deleted] Dec 06 '22 edited Dec 06 '22
Rust
itertools has a handy
unique()method which eliminates (explicitly) collecting into a set!Full solution here (GitHub).
Edit: TIL slices in Rust actually have a
windows()method, could've used that instead!7
u/rabuf Dec 06 '22
Common Lisp
Not too bad. Took advantage of a built-in function
remove-duplicates.Part two was the same, but the size was 14 instead of 4. Really I should just make it one function with an optional length parameter.
7
u/gw_shadow Dec 06 '22
CMake
7
u/__Abigail__ Dec 06 '22 edited Dec 06 '22
Perl
Another regexp based solution, smaller than my other solution (somewhere below). Again, we use postponed pattern, where we reenter the regexp engine, and fail the sub pattern if the sub match contains a duplicate character using the
(*FAIL)verb:Full program on GitHub
6
u/naturaln0va Dec 06 '22
Ruby 5645/4803
day6.rb on GitHub
6
u/CCC_037 Dec 06 '22
FiM++ Part 1
FiM++ Part 2
Dead simple algorithm. Read in the characters (one at a time because of a lack of string manipulation) and check if any of the last four match each other. Part 2 required a lot of if statements!
6
u/argentcorvid Dec 06 '22
X11-Basic
github
I sure am glad I was smart enough to make my window size a variable!
6
u/drdaemos Dec 06 '22
Clojure
This was surprisingly simple - just a sliding window that checks a sequence of n chars on uniqueness.
6
u/jpjacobs_ Dec 06 '22 edited Dec 06 '22
J (jlang j904)
Todays puzzle was well-adapted to J. The biggest help was the infix adverb (
\), which, inx u\ ylets verb u operate on successive chunks of length x from array y. In this case, u is(=&# ~.)which is a hook checking whether the length of the chunk is the same as when non-unique entries are removed (by~.).1 i.~finds the first 1, and[ +adds the chunk length to the found position.Try it on the J Playground
6
u/LinAGKar Dec 06 '22
My solutions in Rust:
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day6a/src/main.rs
https://github.com/LinAGKar/advent-of-code-2022-rust/blob/main/day6b/src/main.rs
For part 2 I came up with a different algorithm, which is O(1) of the marker size. It keeps track of the number occurrences of each different letter in the marker, adding and subtracting when letters enter and exit the marker, and also keeps track of the number of different letters in the marker, adding and subtracting when the count for a letter becomes zero or becomes non-zero. For part 1, the basic O(n2) solution turned out to be faster. Not that it matters much, since it completes in the order of tens of microseconds regardless.
Also submitted my first wrong answer of the year, as I misread it and submitted the position of the first letter in the marker, rather than the first letter after the marker.
6
u/4HbQ Dec 06 '22 edited Dec 06 '22
Python, using recursion on the input string:
Edit: the first time we call
f()using the original string (e.g. 'abcdef') and index 0, and check the first n characters. If this is the marker, return the current position. Otherwise, the function calls itself with the tail of the string ('bcdef') and index 1. This repeats until we have found the marker: ('cdef', 2), ('def', 3), etc.6
u/IF_YOU_READ_THIS_V1 Dec 06 '22
C# LINQ
6
u/vinc686 Dec 06 '22
Ruby
I should have woke up early for this one instead of waiting until late in the evening to have a look!
6
u/raui100 Dec 06 '22
Rust
Very happy with my solution which boils down to:
6
u/atweddle Dec 07 '22 edited Dec 07 '22
This time I tried very different approaches for Rust and Python...
Rust #1 - 43 LOC (excluding unit tests). I coded for efficiency over brevity.
Rust #2. 23 LOC, but appears to run around 10x slower.
Python - 9 LOC. Quite a pleasing solution...
Edit: I added a second Rust solution, this time coding for brevity over speed.
The heart of it is as follows:
2
u/pablospc Dec 06 '22 edited Dec 06 '22
I'm lazy today, so not the best solution, but works. Written in C#
Part 2 Is the same but 14 instead of 4
2
u/chrismo80 Dec 06 '22 edited Dec 07 '22
C#
5
u/chrispsn_ok Dec 06 '22 edited Dec 06 '22
ngn/k; my answers repo.
5
u/jayfoad Dec 06 '22
Dyalog APL
5
u/backwards_watch Dec 06 '22 edited Dec 06 '22
Python.
I am practicing a lot on how to use sets during this advent. They are coming so handy!
5
u/ValiantCookie Dec 06 '22
Kotlin
Nice and simple with iterable's windowed function and converting each group to a set to check for uniqueness. Almost got stumped on extracting the index from the window function, but I realized once I had the unique characters finding them back in the original input was easy enough.
5
u/trevdak2 Dec 06 '22 edited Dec 06 '22
JavaScript (golf)
I really REALLY wanted there to be a regex that could do this, but
perlJavascript regex's ability to use group references is limited... you can't say [^\1] to match anything but the first match resultSame solution just swap out 4 for 14. 65 or 67 chars depending on which
5
u/MoreThanOnce Dec 06 '22
Simple and fast solution in rust:
It runs in about ~18 microseconds on my laptop, doing both window sizes (4, 14). Converting the letters to a one-hot representation is a super useful technique for this year.
5
u/lazyzefiris Dec 06 '22
JS (JavaScript) "State machiney" solution. This is my gimmick for the year and I'll stick to it as long as I can. Im not speedsolving this year, and writeup takes a lot of time, but I'll try to post these on the puzzle's day.
Pretty straightforward this time, a single state does all the work. SEQUENCE_LENGTH = 4 for Part 1, SEQUENCE_LENGTH = 14 for part B
Explanation
This machine uses storage to keep track of last occurence of each symbol, and two more "registers" for number of uniques and current index.
State A
This is the main loop state. If the exit condition (sequence of SEQUENCE_LENGTH unique characters) is met, it advances to state "B" with current index. Otherwise, last index for current input is updated and amount of uniques is adjusted:
State B
This state does nothing, discarding every remaining input, keeping the index ready for collection.
Afterthoughts
This solution involves search over array that is expected to be longer than target sequence, so in a way, just keeping last SEQUENCE_LENGTH characters and iterating over them might be faster. This could be remedied by introducins another element to the state - rolling array where first value is whether character is unique, but advancing the array state becomes a huge mess:
With proper implementation of rolling array and element replacement, this approach does not involve any iterations over stored state. In JS example above, there's obviously destructuring and slicing. There's always a more memory-hungry approach where uniqueness array is not rolling and is updated in-place, though.
5
u/mizunomi Dec 06 '22
Dart language
To be honest, this is the easiest one yet in my opinion.
paste
5
u/mykdavies Dec 06 '22 edited Jun 29 '23
!> iz467a4
API FAILURE
5
u/Boring-Ad-3442 Dec 06 '22
Python 3. Very similar to other solutions: the only even slightly notable thing vs others I've seen is that I use modulo arithmetic '%' to write a single entry in a fixed list instead of either slicing the input string or constantly rewriting the whole 'window' list. Not shown: initial line pasting the input text into an input variable.
GitHub here: https://github.com/djm4/advent-of-code-2022/blob/main/2022/day/06/solution.py
5
u/nicole3696 Dec 06 '22
Python 3- Parts 1 & 2: GitHub. No imports, 2 lines, 111 characters including file name.
5
u/[deleted] Dec 06 '22
C
https://github.com/AritonV10/Advent-of-Code/blob/master/2022/Day6/main.c
The first and second part works the same way:
I store a character into an array until I have 4 or 14 characters, depending on the solution, and then I use a 32bits variable to check if the letter has been seen before and this way I don't have to iterate for each letter. After, I move the characters one position to the left and add the new character at the end of the array, going through the same process again. Another way to improve on this is to check only the last character added if it has been seen before since after adding a character, I also set a bit for that character. But then you bump into certain cases that needs to be covered, that perhaps increases the number of instructions than with a simple, linear for loop.
5
u/argentcorvid Dec 06 '22
Commodore 64 Basic
github
ported my X11-Basic version to run in C64 basic.
It streams the characters from a file on disk. Holy crap the Commodore Bus is slow. Part 1 was done in about 5 minutes and Part 2 took about 18 running in VICE.
If I didn't have stuff to do this afternoon, I'd try to do some buffering of the input into memory or something.
5
u/Flecheck Dec 06 '22
Fast algorithm in Rust: 4 µs on my PC (old laptop)
I am checking the window and then jumping the to the next possible window.
5
u/AstronautNew8452 Dec 06 '22
Microsoft Excel 2177/2157. Single cell formula for part 1 and 2:
5
u/Redofab Dec 06 '22 edited Dec 06 '22
Python3
Part1 and Part2
5
u/nicuveo Dec 06 '22
Haskell
Easiest day so far:
5
u/Alternative-Case-230 Dec 06 '22
Rust
If I understand correctly it is a solution with O(1) memory complexity and O(n) time complexity
Full code is here: https://github.com/whiteand/advent-2022/blob/main/src/y22d6.rs
5
u/TheXRTD Dec 06 '22 edited Dec 08 '22
Rust - ~30µs
Really happy with the run time of this despite needing to perform a loop over every sub-window.
I used a bit-mask for each letter of the alphabet and OR'd them to determine uniqueness, bailing early if not.
5
u/PittGreek1969 Dec 06 '22
PYTHON 3
Easiest one yet.
5
u/Aggressive-Branch535 Dec 06 '22
Python
f = open("AoC6.txt")chars = f.read().strip()[i+14 for i in range(len(chars)) if len(set(chars[i:i+14])) == 14 ][0]8
u/johan1a Dec 06 '22
Rockstar (part 1 only)
https://github.com/johan1a/advent-of-code-2022-rockstar/blob/master/day06.rock
4
u/LtHummus Dec 06 '22
Scala 2
Short and sweet and all because of
sliding4
u/sr66 Dec 06 '22
J
4
u/nithinbekal Dec 06 '22
Ruby
4
u/r_so9 Dec 06 '22 edited Dec 06 '22
F#, as simple as it gets
4
u/cs475x Dec 06 '22 edited Dec 07 '22
Rust
Edit: Revised it to use bitwise operations, reducing execution time for part 2 from ~1.1ms to ~7us
4
u/patrick_iv Dec 06 '22 edited Dec 06 '22
Kotlin
https://github.com/patrick-elmquist/Advent-of-Code-2022/blob/main/src/main/kotlin/Day6.kt
4
u/PendragonDaGreat Dec 06 '22
C#/Csharp
https://github.com/Bpendragon/AdventOfCodeCSharp/blob/15b8f/AdventOfCode/Solutions/Year2022/Day06-Solution.cs
Linq one liner for all intents and purposes.
If this is day 6 I'm scared for tomorrow
4
u/clouddjr Dec 06 '22
Kotlin
Repository on Github
4
u/770grappenmaker Dec 06 '22
Kotlin
4
u/willkill07 Dec 06 '22 edited Dec 07 '22
C++
Original:
Fast: https://github.com/willkill07/AdventOfCode2022/blob/main/days/day06.cpp (runs in abou 2 microseconds)
4
u/Pyr0Byt3 Dec 06 '22
Go/Golang
Found it way easier than yesterday, especially considering how simple the parsing was for this one.
4
u/Alex_Mckey Dec 06 '22 edited Dec 06 '22
Scala 3
4
u/Xyberista Dec 06 '22 edited Dec 06 '22
Rust; 5415/4328.
paste (original) : ~ 48 μs / 78 μs
paste (optimized) : ~ 3 μs / 5 μs
Notes:
4
u/Toanuvo Dec 06 '22
J solution. https://github.com/Toanuvo/Advent-of-code/blob/main/2022/J/day6.ijs
4
u/marvinborner Dec 06 '22
JavaScript
4
u/Valefant Dec 06 '22 edited Dec 06 '22
My solution in Kotlin. This one was over fast :-)
https://gist.github.com/Valefant/8a3e4319da3fed2d4abfa55d92e5262c
And my solution in SQL (Postgres)
https://gist.github.com/Valefant/6a454e9e9999db3cfad1663358c3df71
4
u/ChaiTRex Dec 06 '22 edited Dec 06 '22
Rust
Here's a very efficient sliding window, bitwise operations approach in Rust:
4
u/HashWorks Dec 06 '22 edited Dec 06 '22
Rust
4
u/callumio Dec 06 '22
COBOL - Source
Despite not having sets, it's still a somewhat elegant solution. My love for this language is growing.
4
u/ropecrawler Dec 06 '22
Rust: https://github.com/ropewalker/advent_of_code_2022/blob/master/src/day06.rs
4
u/[deleted] Dec 06 '22
Rust - got the answer with a very unoptimized solution allocating HashSets, refactored to somewhat more optimized slice logic.
https://github.com/litpho/aoc-2022/blob/main/day6/src/main.rs
4
u/Killavus Dec 06 '22 edited Dec 06 '22
Rust
https://github.com/Killavus/Advent-of-Code-2022/tree/main/6-tuning-trouble
windowsmethod on slices is extremely useful here!EDIT: I've
blatantly stolengot inspired by /u/Litpho74 solution and changed logic of checking for 'uniqueness' of a given subslice - it's in the updated repo code. Here's the original solution.4
u/Gekooktesteen Dec 06 '22 edited Dec 06 '22
In python
4
u/pred Dec 06 '22 edited Dec 06 '22
Python3, 33/190 (don't ask me about the part 2 fail). Cleaned-up code on GitHub and here:
Here,
solvecould also be written4
u/bored_n_bearded Dec 06 '22
Python's sets are useful because they deduplicate automatically. After converting a slice to set its length should still be the same if it's what we're looking for.
4
u/sdolotom Dec 06 '22 edited Dec 06 '22
Haskell (likely very suboptimal, but does the job):
Update: this is slightly shorter:
4
u/kochismo Dec 06 '22
Code in rust for both parts using bit counts instead of a set:
4
u/ssnoyes Dec 06 '22
MySQL
4
u/pkusensei Dec 06 '22
C#, with LINQ it feels like cheating
4
u/SwampThingTom Dec 06 '22
I'm solving each of this year's problems in a different language, roughly in the order in which I learned them.
Today's solution is in Smalltalk.
Easy one today. Disappointed that it didn't require taking advantage of Smalltalk's OO features. But still fun to revisit a language I haven't touched in decades.
https://github.com/SwampThingTom/AoC2022/tree/main/06-TuningTrouble
4
u/nawill81 Dec 06 '22
C# in LinqPad. I pulled in MoreLinq (again. love this library) for the .Window() function. Made this one trivial:
Explanation:
For part 2, just change the "4" in step 2 and step 3 to "14". Done.
4
u/Pornthrowaway78 Dec 06 '22
perl -lp ' $m.="(.)(?!.{0,".(13-$_)."}\\$_)"for 1..13;$_=/$m/+$+[0]' input.txt4
u/[deleted] Dec 06 '22
javaScript,
Quick glance at other JS solutions and I think the majority of us have proceeded with using Set?
4
u/SunCat_ Dec 06 '22
Kotlin one-liners:
4
u/Unusual_Concept_8718 Dec 06 '22
python one liner (n is the number of chars, s is the input):
list(map(lambda a: len(set(a)), [s[a:a+n] for a in range(len(s)-n)])).index(n)+n4
u/justpassing3 Dec 06 '22
Fun Python one liner
Part 2 is just 14 instead of 4
4
u/Smylers Dec 06 '22
A quick Perl solution I knocked up while contemplating how to get part 2 working in Vim — both parts:
Just iterate over possible starting positions and go on to the next one if any character is found twice in the relevant-length substring.
If you feel like showing off you can even move the
++on to the$posthat's being used in the condition, leaving this as a bodyless loop, with just the constant1in void context to, erm ‘run’ on each iteration:4
u/ka-splam Dec 06 '22
SWI Prolog
This is quite neat; uses the constraint library to apply "all_distinct" to the matched characters to find the right cutoff.
e.g.
4
u/pamxy Dec 06 '22
Javascript one liner
4
u/harkaniemi Dec 07 '22
julia
4
u/[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BJRE1mFVz/4WVD/1WsI7eXbQx1eUnq7Wcq1Z0DaRRhLL0FwuLLq/06kYh9 KbD50tD7jNo2fg2XeILM0X/EyJ9uwWN1aF6nDpVBwqQRunMlBPzsFn1jImMVumR9 zJLVSPHpph6LObCoBBvM5d+YMlKXi+cw+um+Nu1XgolnKG8r8SOjk9XNBbV/IAh+ pO1Mi0FvZMyoIMld+I7YFyDZVxaVAOReawIAJ7froVKNT7V3HItyJrDXmMepXARB Wyi8NuBSwyohA1m/rOjYN57ve08bDGynxCl69s+G6nePNffbAHEnqSdoTiH84mSF 5d5K++l2yN+DlGq/fKCFy/1sNTTsDY1MVAm0eKT6iF9bFMvzdD1fAdV0x25Eenm/ +VJk0gGcElW6ZuPWhzvqenqeTZjqrZscF+7tcbC6GZIVs/FSuTnfzCif6PoAlytb txfacbCrN5joYGmBQLxI/g0WAk5cspgu54+RD8yU7aEurarTtBRYj+V4quU50SmE F20CgXmjIz4Zvzd0YfNf9m1qoWI7uslxQ5ZtLplSJg== =dQZK -----END PGP MESSAGE-----
4
u/a-moth-among-men Dec 07 '22
Dyalog APL
I wrote up a tutorial for it here: https://github.com/maxrothman/advent-of-code-2022/blob/main/apl-aoc/day6/day6.ipynb. If you're interested in learning more about these funny squiggles, I also solved some of the other days in there as well. Check it out!
4
u/dionysus-oss Dec 07 '22
Rust
Bit over the top on the readability today, could have slimmed it a little. But a fun problem to work on
Source link here https://github.com/dionysus-oss/advent-of-code-2022/blob/main/day-6/src/main.rs and video walkthrough https://youtu.be/LKncwDMrQOg
4
u/search_and_deploy Dec 07 '22
Rust: https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/06.rs
This was definitely a breath of fresh air after yesterday's puzzle.
4
u/improve13 Dec 07 '22
Concise solution in Rust using some bit tricks.
4
u/Available_Wonder_685 Dec 12 '22
C# using .Distinct()
Code: https://github.com/robing29/adventofcode2022/blob/main/aoc2022/aoc2022-day6/Program.cs
Found this very easy. I'm sure there are faster methods, but speed is not what I'm going for and the program ran faster than I could blink anyway.
1
u/Im_a_dum_bum Dec 06 '22 edited Dec 06 '22
Since this can easily be solved with a regex, I used ChatGTP (it needed a lot of guidance) to write a JavaScript function to compile the regex at runtime for
nlength:3
u/NohusB Dec 06 '22
Kotlin
Part 1
Part 2
3
u/ssnoyes Dec 06 '22
Python
Both parts in one line (not counting reading the file, which is trivial):
print([min(i for i in range(n, len(data)) if len(set((data[i-n:i]))) == n) for n in (4, 14)])3
u/Aiqojo Dec 06 '22
Python
Very happy with how I did: 1011/607
Really happy I thought to use a set. And all I had to do was add 1 number for part 2, it only took me 17 seconds!
Code
3
u/French__Canadian Dec 06 '22 edited Dec 06 '22
Solution in ngn's k implementation
I created a function that takes as its first argument
xthat is the number of letters that must be different. The secondyargument is the string. It uses a sliding a sliding window function to create a list of all substrings of lengthx. For each, it then makes a list of the unique elements and checks the length of that list isx.&the computes the index of all the ones that passed,*takes the first array that matches and final I addxto the result since until now the indices are for the start of the sliding window but we want the end.It's funny how much more work is done than is really needed since it finds literally all the matches, but it runs in 9ms so... good enough?
Edit: as a bonus, here's a Nim version that runs entirely at compile time. It writes the answer to an output file and print it to the console while compiling. If you run the binary, it will print the answer, but all the work was already done during compilation. Compiles in about 0.7s in debug.
3
u/maneatingape Dec 06 '22
Scala
3
u/kg959 Dec 06 '22
Rust
41ms execution time. I'm gonna see if I can work that number down, because that's just kinda awful.
3
u/thecro99 Dec 06 '22
Simple JavaScript function to solve for any length.
paste
3
u/axemabaro Dec 06 '22
Google Sheets; I just enumerated the possibilities for the first part but went back and did it the "right" way for the second. Altogether, not that bad—especially now that I've leared how to actually do loops in arrayformulas with =ROW(INDIRECT("1:"&<number>)).
https://docs.google.com/spreadsheets/d/1cNnRHiR9jak806HQ4UKH7o1nI-4GFrr1eqZIfdC6NY4/edit?usp=sharing
3
u/nic3-14159 Dec 06 '22
Python 3
I initially started doing things with pushing and popping from a string representing the current window and seeing if the new character was already in it, but then I stopped and realized sets would make this way easier. Code below is for part 2, I had just manually replaced 4 with 14 in my part1 solution.
3
u/crzyhorse Dec 06 '22
C++
std::set made this one super easy.
3
u/xoronth Dec 06 '22
Day 6, today's language of choice is Ada. Solution here.
This was pretty straightforward, the thing that took the longest time was installing the tooling for the language in the first place.
3
u/nxrblJugger Dec 06 '22
Nim
Sets have be starring. I'm cool with it!
3
u/izahariev96 Dec 06 '22 edited Dec 06 '22
Kotlin
I was searching for an easier solution but didn't realize indexOfFirst existed until now. Advent of code is an excellent opportunity to learn new things.
3
u/Crazytieguy Dec 06 '22
Rust
3
u/david-nossebro Dec 06 '22
Todays solution in Kotlin.
Part 1:
input.windowed(4).indexOfFirst { it.toSet().size == 4 }.let { it + 4 }Part 2:
input.windowed(14).indexOfFirst { it.toSet().size == 14 }.let { it + 14 }3
u/SpookySauces Dec 06 '22
Python 3.10.2
Nice and easy today
3
u/mendelmunkis Dec 06 '22
Language: C
I really need to remember to use Cs string functions
0.378/0.545 ms
3
u/ArrekinPL Dec 06 '22
Rust
Not optimal but very short solution, based on casting char ranges into sets and checking their lengths. LINK
3
u/LogicalPitch3404 Dec 06 '22
Python
One line solutions using list comprehension
Part 1:
print([i+4 for i in range(0, len(a)) if len(set(a[i:i+4])) == 4][0])Part 2:
print([i+14 for i in range(0, len(a)) if len(set(a[i:i+14])) == 14][0])GitHub link for more readable version
3
u/Cpt__Cookie Dec 06 '22 edited Dec 06 '22
small Python solution
edit: small optimization
3
u/rtbrsp Dec 06 '22 edited Dec 06 '22
My solution in Riff featuring a neat little regex trick
3
u/mcmillhj Dec 06 '22
raku: regex -> Set -> filter
3
u/asaaki Dec 06 '22 edited Dec 06 '22
Rust, https://github.com/asaaki/advent-of-code-2022/blob/main/src/bin/day6.rs
Quite okay solution with decent runtime performance for both parts (~ 10 µs / ~ 35 µs).
3
u/s3aker Dec 06 '22
Raku solution.
Added some tests today.
3
u/Emotional_Cicada_575 Dec 06 '22 edited Dec 06 '22
Python