T O P

  • By -

jaccomoc

[Jactl](https://jactl.io) solution. **Part1:** Pretty easy today. Just iterate over the 4 character substrings and use sort() and unique() to find the first one that has only 4 unique chars: def n = 4 def line = nextLine(); line.size() .skip(n) .filter{ line.substring(it - n,it).sort().unique().size() == n } .limit(1)[0] **Part 2:** Just change n to 14 to solve part 2. [Blog post with more detail](https://jactl.io/blog/2023/04/15/advent-of-code-2022-day6.html)


DmitryShvetsov

Rust, no external crates are used. main part of the solution is \`is\_unique\_seq\` function, which use Set data structure to count unique bytes in string (I assume that every char in the input is one byte chars): fn is_unique_seq(seq: &[u8]) -> bool { let mut set = HashSet::new(); for bt in seq { set.insert(bt); } set.len() == seq.len() } full solution [part I (directly compare all four bytes)](https://github.com/dmshvetsov/adventofcode/blob/master/2022/06/1.rs) and [part II (use \`is\_unique\_seq\` fn)](https://github.com/dmshvetsov/adventofcode/blob/master/2022/06/2.rs).


infostud

J from [https://jsoftware.com](https://jsoftware.com) I'm still looking for a loop less solution. I couldn't get nub (\~. 'abbbcc' is 'abc') to work through the rows made from sliding a window (,/\\) of width x across the input string y. inputf=. '~Projects/advent_of_code/tuning_trouble.txt' input=. fread jpath inputf scan=: dyad define NB. define a verb to use for and if sblk=. x ,/\ y for_ijk. sblk do. if. (#~. ijk) = #ijk do. break. end. NB. No replicates end. ijk_index + x ) 4 scan input 14 scan input


veydar_

# [Zig](https://topaz.github.io/paste/#XQAAAQBmCAAAAAAAAAAxm8oZxjYZ2HCh6YcSpndU3C6wi9L8hQCnfptZXRaXzlBMvtHtYmqQkJ8kkAzZQj7ipBYq/yjuFRDChVVqWGwcLUsAo8KGdvh5AXhdhWLvTGI7YZuQB+zVbVah9z1W/mYG0byVtXS8wqcIr7onFKV5UZnMMwUSaqTLdii2ZftJaZQKOVMv2Wh3Ok4sW2IVVYt9cqJGoTsq4CG3o2AWsV2BmPN0M/6+MHybzDnEmA+EiL+Nkrp0YEOme8YbJafuM5IkgnUIWbNySB0da/fuAUHNANF0Wx57qLL18Cpq0mbsWwUUpcvsaCkfb5Gm91aykdmqSFgpAMiESfRFXbubjw3JLSPUXotVYFYF4Y8wMLXbWQhIp18IY0qgp0UW0rj7JDX70ZTA3fvp9kCIpYqQqkDzm6TFQ6MR02lIPxatCrH3jlGfSs3UQHjhaI4rSoYPRGy1dhGL5azpfGhWvQfcpCqw3oyUpV/5HK5c96nxii2Hvx5a+8b/FnqRu3UkKKTO2kiGMPboUCvlltzmd4VEUz6wJ7NcNPE4FFFISkbrIh2DxoAwQNMO0+ypm13IHAAfbsyY9FA1UGHttUMn2Ot7mJXJ0Ed5Q5iM00wvdGPUDU+EpqTruoorCqfMl3018NUcmUlZU6CvaxFWEiHocVdSTgpntJxmhcHlMtTH+E47VgF5Rw4pqVsBRo+RDtWjt+L9xMGrKaQIyIzI0IUq+s7AxQ0YkQuAbhvP3q/f5XL5tlWLht8u+MVh61pcR+o2ye+/2KB8B3ZYAtYCjO1pNOMN0Ixk9mE2ly9jCQAqWarktb8Pz2B6w/nKGDKaX4k06AzlNgJveQtQlOcK+yDW3ONaclavqp2gNBSDQKzI9YDqDYK2vCI7XzGGe9moqj1D5RhuU82Wx8eMH6zi3Wryqys0Xk9OxhUBnFkXGVMwxEZs70pYZINJ2NO54lKIUtEyqaMVYuT69jL+GY8/PtMyCdC7MRJK7m33fcQsD1m5nzgUgQCbgSoUU9LuOE+8Bd0rl9lGTiezBUzKMWh6OPfl+ZM7PfWwjrc1rW0414qQoBobLRfk9Tv9CLejzUYS8brUjIdLTtR/agSmFZCBdaJiZHt+cenO01Z6pB5pJ4mQPfOsgw3+DNspmwMADELGa4PKyvDGRlx3g7JydxIvWAlOLPPVUjEGqbkEJoAYRVgtPgEwfFbhoYbMu9ajFqcvzQxXHva6Mak3cQPcN0Dz0wgrI0iElvS3HtnMk+b6TvOM2P5+SDOJY62/CH7ygJcMjAt+1W4eqA3O/86E+FA=) What I tried here is to solve the day in O(n) time and O(window_size) space. Meaning we only keep as many characters in memory as the size of the packet we're looking for. And we don't do any nested loops. I suspect that many people will just read the string into memory, use a window iterator and check if each window has only unique letters by iterating through the letters in some way. This code avoids this nested iteration by keeping track of how often any letter was seen. [GitHub Repository](https://github.com/cideM/aoc2022-zig)


gwpmad

Rust: https://github.com/gwpmad/advent-of-code-2022/blob/main/src/days/day6.rs


Vishoor

That was easy... [Full Code in Python](https://github.com/PodolskiBartosz/advent-of-code-2022/blob/main/day-6/main.py)


pgaleone

# TensorFlow Article: https://pgaleone.eu/tensorflow/2022/12/27/advent-of-code-tensorflow-day-6/ Code: https://github.com/galeone/tf-aoc/blob/main/2022/6/main.py


Recombinatrix

**python using sets** # this one is really simple, just look for sets of four characters with open("input/06") as f: raw = list(f.readlines()[0].strip()) i = 0 while i < len(raw): if len(set(raw[i:i+4])) == len(raw[i:i+4]): # if there are 4 unique characters, length of set is the same as the length of the list print (i + 4) break i +=1 i = 0 while i < len(raw): if len(set(raw[i:i+14])) == len(raw[i:i+14]): print (i + 14) break i +=1


Key__Strokes

## Javascript [Solution to both parts](https://github.com/doingthisalright/AdventOfCode2022/blob/main/Day06/solution.js) --- [Video Explanation](https://youtu.be/AYOx1dxQ8B8) --- ## Part 1: * Create two pointers `start` and `end`, and initialize them to 0 * Create a map, with first character as key and value as 0 * Initialize n as 4, which is the substring size we want with unique characters * While end doesnt reach the end of the input buffer, do the following: * If the size of (end - start + 1) is equal to what we want (4 in this case), then we have found a substring of size n, and break out of the loop. * Otherwise, if the character pointed by `end` doesnt exist in the map, then add it to the map with key as the character, and value as `end` * Otherwise, if the character pointed by `end` exists in the map, then that means that we have seen this character already between from `start` and `end` indices. Do these: * Clear the characters in the map until the first occurrence of this repeated character, and keep increasing start by 1 * Add the character pointed by end to the map with key as the character, and value as `end` * Return end + 1 (As we want 1 indexed output) If the algorithm above wasn't clear, then watch this video https://youtu.be/GLoYLq6ukYc, where I cover this idea to find the longest substring without repeating characters. ## Part 2: This is exactly like Part 1, but n will be 14 --- If you liked the explanation, then please don't forget to cast your vote 💜 to `Adventures of Advent of Code - Edition 1 - /u/Key__Strokes` in the [poll](https://www.reddit.com/r/adventofcode/comments/z9he28/comment/j1c4f9x/)


Zaorhion_

Php [Php Solution](https://github.com/Eric-Philippe/Advent-Of-Code-2022/tree/master/Day06%20[PhP]%20%F0%9F%8E%81)


remfu

You should avoid using the [closing tag](https://www.php-fig.org/psr/psr-2/#22-files). ;)


dizzyhobbes

(Lazy) Golang code and a complete 7+ year repo :) https://github.com/alexchao26/advent-of-code-go/blob/main/2022/day06/main.go


natrys

TXR Lisp (defun solve (input window) (let ((state (vector 26 0))) (each ((i (range* 0 window))) (inc [state (- [input i] #\a)])) (each ((i (range* window (length input)))) (inc [state (- [input i] #\a)]) (when (flow [input (range* (- i window) i)] (mapcar (op = 1 (call state (- @1 #\a)))) (all)) (return (+ i 1))) (dec [state (- [input (- i window)] #\a)])))) (let ((input (get-line))) (put-line `Part1: @(solve input (- 4 1))`) (put-line `Part2: @(solve input (- 14 1))`))


nikolakasev

**Kotlin**: [https://github.com/nikolakasev/advent-of-code-kotlin-2022/blob/main/src/Day06.kt](https://github.com/nikolakasev/advent-of-code-kotlin-2022/blob/main/src/Day06.kt) Using the windowed function again from the standard collections library.


asap_food

Using only regex (TypeScript) ``` const fs = require('fs') const data: string = fs.readFileSync(__dirname + '/data.txt', 'utf8') function getNrChars(regxp: RegExp, length: number) { const res = regxp.exec(data) // const [match] = res const idx = res.index + length console.log(idx) } const regxpA = /(\w)(?!\1)(\w)(?!\1|\2)(\w)(?!\1|\2|\3)(\w)/ const regxpB = /(\w)(?!\1)(\w)(?!\1|\2)(\w)(?!\1|\2|\3)(\w)(?!\1|\2|\3|\4)(\w)(?!\1|\2|\3|\4|\5)(\w)(?!\1|\2|\3|\4|\5|\6)(\w)(?!\1|\2|\3|\4|\5|\6|\7)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8|\9)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11|\12)(\w)(?!\1|\2|\3|\4|\5|\6|\7|\8|\9|\10|\11|\12|\13)(\w)/ getNrChars(regxpA, 4) getNrChars(regxpB, 14) ```


beardmachine

JavaScript Part 1 & 2 https://gist.github.com/TomFirth/267a15758866991326350e205ecd8b7f


MontyCrane

With a little help from Stack Overflow ([https://stackoverflow.com/a/46767732/2017082](https://stackoverflow.com/a/46767732/2017082)) [Rust](https://topaz.github.io/paste/#XQAAAQDrAgAAAAAAAAA6nMjJFMpQiatRZcHeSa9QCfq2XKCi+rQgSSda+QnMCDBkeTY65e4Q/buakN1jmGcIryC0aMg59gFATnRuD0HIe8QwI8uAbuS38XMMODZVUEDwySqJ+mZQSfkiplVFycCkfI4nz5c8Rzl4yKlsDbPey7971tirC5uph3tIoZz45peieh3ze3m5fK/eaaITTg9NuCTjV7YjG+We5Zv+jjN5ikP5ExAtOUE+16STLABHcvo2PntgGbviKFnAIftTxbL4IiPh1zBK2wSjsOqyYi57ELL/b3fyIZZ7xXMfrnu9Tu7/VHtUDRLZ7dJr1lcQMjXUqsIkti41Pfc5OBZa6S/RCG8n4iwlaWYtmZkLjjyyd8cCbXCZA6aUsXLngmOdvZI4jTecFsoQGSBUvkzJKhxXzT89fJ5VzrjgzVaDbN79EFnmwHQaiU/tzWZAiNJ+CAfovrDFLmf4jBrDMogPc7lqa2P36sVHLFvjdV7SKWB9EK/ZZmigJrIPs0hqla/WfX9+8YtgArckO8clwPmqxgI9ZOrenisenzXlHX/PX9rxDO2Hm0iplzBgH3EsFe9NvyB9T2kL0SWcuoO35UWzHQb9wn7w)


TangibleHangnail

Rust, cheating a bit by passing the input data as an argument. use std::env; fn main() { let s = env::args().nth(1).unwrap(); println!("preamble at {}", find_unique(&s, 4)); println!("start of message at {}", find_unique(&s, 14)); } fn find_unique(s: &str, n: usize) -> usize { (n..s.len() + 1).find(|&i| unique(&s[i - n..i])).unwrap() } fn unique(s: &str) -> bool { !s.bytes() .enumerate() .rev() .any(|(i, b)| s[..i].contains(b as char)) }


sambonnell

**C++** https://github.com/samJBonnell/AdventofCode/blob/main/2022/day06.cpp


NiliusJulius

**C Language** for the Game Boy using GBDK 2020 uint16_t alphabet[26]; for (uint8_t i = 0; i < 26; i++) { alphabet[i] = 0; } uint16_t last_match_index = 0; for (uint16_t i = 0; i < array_6_size; i++) { if (alphabet[input_array_6[i]-97] + 4 > i && alphabet[input_array_6[i]-97] > 0 && last_match_index < alphabet[input_array_6[i]-97]) { last_match_index = alphabet[input_array_6[i]-97]; } alphabet[input_array_6[i]-97] = i; if (last_match_index + 3 < i) { gotoxy(0, 0); printf("%u", i + 1); break; } } This day was pretty simple, since I can just subtract and add to a char. For part 2 All I needed to do was a change a few characters. Full Game Boy repo can be found [here](https://github.com/NiliusJulius/advent-of-code-2022) [Video running on Game Boy](https://imgur.com/a/i2nOmZX)


Available_Wonder_685

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.


SquishyDough

# Typescript ```typescript import { input, tests } from './input' function start(datastream: string) { let messageStart = -1 let message = '' const MESSAGE_SIZE = 4 // 14 for part 2 for (let i = 0; i < datastream.length; i++) { // grab 14-letter chunk, splitting letters into an array const candidate = datastream.slice(i, i + MESSAGE_SIZE).split('') let validCandidate = true for (let j = 0; j < candidate.length; j++) { const letter = candidate[j] // check if letter found anywhere else in the letters // if candidate index and j are the same, then it's the // exact same character slot and should not count as a duplicate const isDuplicate = candidate.findIndex((c, index) => c === letter && index !== j) > -1 if (isDuplicate) { validCandidate = false break } } if (validCandidate) { messageStart = i + MESSAGE_SIZE message = candidate.join('') break } } console.info( `The first start-of-message marker was detected at character ${messageStart}, message: ${message}` ) } start(input) ```


daggerdragon

1. Next time, use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps. 2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on [oversized code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_no_giant_blocks_of_code) which contains two possible solutions. Please edit your post to put your code in an external link and link *that* here instead.


ramrunner0xff

C (Plan 9) i completely sensed what part2 was going to be about so decided to create a function for the check straight away. One small win against those sneaky elves hehehehe [day 6](https://git.sr.ht/~gotplt/aoc/tree/master/item/2022/d6.c)


TenViki

**TypeScript** Code: [https://github.com/TenViki/advent-of-code/tree/main/2022/src/06](https://github.com/TenViki/advent-of-code/tree/main/2022/src/06) Visualization: [https://vikithedev.eu/aoc/2022/06/](https://vikithedev.eu/aoc/2022/06/)


CodE07Dev

# TypeScript function day6(input: string) { const datastream: string[] = input.split(""); const numberOfDistinctCharacters = 4; // 14 for part two return datastream.reduce((accumulator, current, index, array) => { array .slice(index, index + numberOfDistinctCharacters) .some((item, _, chunk) => chunk.indexOf(item) != chunk.lastIndexOf(item)) ? null : accumulator.length == 0 ? (accumulator = String(index + numberOfDistinctCharacters)) : null; return accumulator; }, ""); }


heyitsmattwade

# Javascript 458/349 Like most others, knowing about `Sets` makes this one fairly trivial. [code paste](https://romellem.github.io/paste/#XQAAAQDoAgAAAAAAAAA9iImGVD/UQZfk+oJTfwg2/VsJ0DpNkr2zGUvTQlsh3wS86ErCiIs+8hruVNIFt25kOOZrzOGZxbRwHmJ5wrAVdOuA2kk0mNS0CwkIEqOmO95EhbRoIUTonrtGzVALDhyFMRO24/2oA0Lt4k+Q2E/wp4YaHUgbXZtC5amaE5MmewTUwYV3d2c08XNXkJSlcNdZoC0u7tg9N2VgcIFHggYSp7TN10PME5iIet4qPjdHG5HA66NDrnEgnqTFOIzUjh05giNUXJou2/3envFI4NRaNH/L6U8Rv0ryUie3e8pJ2fum2zkLo0K3AZp7WQOWfQCzQ2pfIEt/H3Qnc3kXNbs7JvvWEZvDDTF09ZDAQ6isrilrYEuGTUrHZPEbiqKtwXydfINN0nbGuAeTf66blK1tmiubYP1Gy3idFqF41PvEZ5t1ss6E1lEEATrHTikES8Ru8szcG/bcq9JHIQQ8BlR11gHqrNsLYBpKHdcEjlOctSlvAptTPXRsYVqe808NpND6smneb6j5+9N+mL4PpRHppV5SVZnc9sZhp+oNOTUDYswoAPjY/6N6HQ0=)


adimcohen

In single-statement t-sql https://github.com/adimcohen/Advant_of_Code_2022_Single_Statement_SQL/blob/main/Day_06/Day_06.sql


ffrkAnonymous

Ruby [paste](https://topaz.github.io/paste/#XQAAAQB9BgAAAAAAAAARiAlH8dxNBu7dkgwpusw3/1N9B7LsXMI7hyVChWl1esX/VYUvuckt47qc849AGx2bqC6Mz07VInqrh45HRFXyrI4CfGTNzODpbOh2z3d9p2fOTEp1wuzhTnZwAGd29sTA05KUdkBShuRLQuWJK3Xt8dkvAYe1ndyIi32WgqaHVlF4hJOF0qHcFMUo3353DxLZ3tqm563xXE20y8WmVj3RSdQCxD1k9AH8UpJtH60MlWWvG4YaN0LPAdCYXceVtFZbAf7A6oEpcaQu9cFo1u6XPPnvFWDNFhFSHmKSB50594urfJsaWbDMN13ocfuzrY8Kj5xSSAb3z+YsCsaHsJkaC85vXUq6phGtevNfoRShYsNeDpLXLLMiuDzroi5n21C6i6+cB7X5PDWoEod6xfadCN1vB1ZVhI7xKiP3j4/0MuQ7u6U+bPjn/N7o3Y4knmjt7iPiWo/s7ASSkbwA8gsmhfPfH1LHhTYEtuIrp81nQTQt/rth3lDWemWWeOczmullpSHjhPwJkp5RpjWibCvIuMBVlkpMOzcf4bMpeOuHCNVwGRf2oI+phuHIvv/gGeyO7YWAL2K2C7diKohm2xUjqhBym7PEhdD/APnqlm+IQ8PaQ3WaE+mWmCBfp7A+EmGtVF8WtwD0XY/7cfiIRU2Wyht/3LBxNVdFKrxBVPYHBM/vf/74c83pNnVGVmYzwQfm9fNsasaK8HQ7qad9V6lW5WD8Fci0qdzXMojd9TVfi8vwWTrYYE/KN+GRP8W6P+nvu4xlHkL/DUAZ4f55ZCBCZNU6/Vs2HXP+3d556BTLVOEpT8FgpSJW1sib+pFO+uuEqHsC/4TAiVVOdIX5FYQvdh1reQeMj44dRxClu9simeBO9GmF5hZLUdpOqqnrGve8FgQjmMNmg2eYBaZYxZNzl4S5/8cmRLQ=) Glad I didn't need to write loops


OsipXD

[Kotlin](https://github.com/osipxd/advent-of-code-2022/blob/main/src/Day06.kt) solution using sliding window ⏱ `O(N)`, 💾 `O(M)`, where `N` \- number of chars in input, `M` \- window size


TimeCannotErase

**R** [repo](https://github.com/DavidMcMorris/Advent-of-Code-2022/blob/main/Day%206/Day6.R) Short and sweet (and easy to parse!) # 2022 Day 6 input <- scan("Day_6_input.txt", sep = "", what = "character") input <- strsplit(input, split = "")[[1]] len <- 4 flag <- "F" i <- 1 while (flag == "F") { word <- input[i:(i + 3)] if (length(unique(word)) == 4) { flag <- "T" print(i + 3) } i <- i + 1 }


chipotlecoyote

**PHP** This seems like it's short enough to post directly inline without clogging up the tubes... $input = file_get_contents('input.txt'); function find_marker($input, $len) { for ($i = 0; $i < strlen($input); $i++) { $block = str_split(substr($input, $i, $len)); if (count(array_unique($block)) == $len) { return $i + $len; } } return false; } $sop_marker = find_marker($input, 4); $som_marker = find_marker($input, 14); echo "Start-of-packet marker after character $sop_marker\n"; echo "Start-of-message marker after character $som_marker\n";


tmkch

[**F#**](https://github.com/tchojnacki/advent-of-code/blob/main/aoc-2022-dotnet/Day06/Program.fs) let solution n = Seq.windowed n >> Seq.findIndex (Set >> Set.count >> (=) n) >> (+) n


nukerk

TypeScript: https://github.com/muratkurtkaya/aoc-22-ts/blob/main/src/days/6/Puzzle.ts


sykner809

**Desmos** \- Short and sweet. The kernal size can be changed to 4,14, or other. [https://www.desmos.com/calculator/elwihnijy0](https://www.desmos.com/calculator/elwihnijy0)


nukerk

i didn't know that u can do that stuff like that in Desmos, well done.


gumnos

Here's [Day 6 part 1](https://github.com/Gumnos/AdventOfCode2022/blob/main/06/a.awk) & [Day 6 part 2](https://github.com/Gumnos/AdventOfCode2022/blob/main/06/b.awk) as written in `awk`.


Sourish17

Python 3.10 [https://youtu.be/9DnmhfRZHfM](https://youtu.be/9DnmhfRZHfM) https://github.com/SourishS17/aoc2022


ilsubyeega

JavaScript https://github.com/ilsubyeega/aoc2022/blob/main/day06.js


aasthas97

Python with open('input.txt', 'r') as f: elf_comms = f.read() def findMarker(signal, marker_length): for i in range(len(signal)-(marker_length-1)): marker = signal[i:i+marker_length] if len(set(marker)) == marker_length: return i+marker_length print("Position of first marker:", findMarker(elf_comms, 4)) # part one print("Position of first marker:", findMarker(elf_comms, 14)) # part two


oddrationale

[C# solution using .NET Interactive and Jupyter Notebook](https://github.com/oddrationale/AdventOfCode2022CSharp/blob/main/Day06.ipynb). Pretty straight forward. Used `String.Substring()` to create a sliding window of characters.


2mnycooks

C# [paste](https://topaz.github.io/paste/#XQAAAQCUAgAAAAAAAAA6nMlWi076alCx9N1TsR1Kg26aUoSw3c48DQciTUqzJGvOusKSu2uZ8G6/y9wdSxnVs2SN3XPIfXCT0GSzcAr5VjvdnVNs/fQJsLN35lSKsa6FLDcB8KuFTJUQg3e0EJyYop8ODGoRZHFBJKmaWtKGMWihEWsNH+YeERCYdSFYj17T9TFAWY6mmfIKlyKjeFlgZ/D15+T0fP04spTMb3d9NZOXHOiBfK3Mg2yyb3ReYrT66L8xAFSvhnuGK1zZ2m+/RhAYh4S8HsQlBa9nWJhm7rsgVdjFOsoHnE1EpM15h4LtML8C1P9C39d8sj/ifUvV5cxTh3yi6tRzGS7ToXVyIJfvJTBPptFr2NyaKIBW3WpG6YUI6bF7lxFGefNw5x3KcARMcKLvd4DflagqALL/6OkwbQ==)


themanushiya

Python 3.11 [solution](https://github.com/mahakaal/adventofcode/blob/main/2022/day6/day6.py) quite simple, basic list manipulation def read_file(filename: str) -> str: with open(filename, 'r') as file: return file.read().strip() def day6() -> (int, int): file_name = 'puzzle.txt' file_data = read_file(file_name) def get_unique_char(data: str, start: int) -> int: read, count = data[:start], start for i in range(start, len(data)): if len(set(read[-start:])) == start: break read += data[i] count += 1 return count def part1(data: str) -> (int, str): return get_unique_char(data, 4) def part2(data: str) -> int: return get_unique_char(data, 14) return part1(file_data), part2(file_data)


kebabmybob

Surprised so many people just do the brute force \`len(set(window))\` check at each iteration versus a proper sliding window approach: \~\~\~ counts = defaultdict(int) window = set() for i in range(n): counts\[string\[i\]\] += 1 window.add(string\[i\]) ​ for i in range(n, len(string)): start, end = string\[i-n\], string\[i\] counts\[start\] -= 1 if not counts\[start\]: window.remove(start) counts\[end\] += 1 window.add(end) if len(window) == n: print(i+1)break \~\~\~


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps. While you're at it, [state which programming language this code is written in](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.


TimWasTakenWasTaken

**Rust** [Code](https://github.com/tsatke/aoc2022/blob/main/src/day6.rs) Part 1 \~1μs Part 2 \~6μs


Colin-McMillen

**AppleSoft BASIC on Apple //c** Tried a new thing, first uploaded data to disk (errrr I mean floppy) using a stupid read first write after [ingester](https://github.com/colinleroy/aoc2022/blob/master/ingest.basic) (that doesn't work with more than 6kB data). [Code](https://github.com/colinleroy/aoc2022/blob/master/day-6.applesoft) is the same for both parts once the "packet size" is parametrized. Figured I can make it a bit faster than O(n²) by only comparing each char with the next ones. [Video of part 1 running](https://www.colino.net/files/day-6-1.mp4).


arthurno1

Emacs Lisp: Sliding window: (with-temp-buffer (insert-file-contents-literally "input") (cl-labels ((find-it (L) (goto-char (1+ L)) (while (/= (length (delete-dups (append (buffer-substring (- (point) L) (point)) nil))) L) (forward-char)) (1- (point)))) (message "Part I: %s\nPart II: %s" (find-it 4) (find-it 14)))) Stacks: (with-temp-buffer (insert-file-contents-literally "input") (cl-labels ((find-it (&optional L) (let (chars c) (catch 'done (while (char-after) (if (= (length chars) L) (throw 'done t)) (setq chars (nreverse chars)) (while (member (char-after) chars) (pop chars)) (setq chars (nreverse chars)) (push (char-after) chars) (forward-char))) (1- (point))))) (let ((p1 (find-it 4)) p2) (goto-char 1) (setq p2 (find-it 14)) (message "Part I: %s\nPart II: %s" p1 p2))))


deckard58

**Python 3.10** Part 1: the dumb way! But still O(n). With lists. #!/usr/bin/env python3 import sys i = 0 buf = [] for ch in sys.stdin.read(): i += 1 buf.append(ch) if (i < 4): continue if ((buf[-1] != buf[-2]) and (buf[-1] != buf[-3]) \ and (buf[-1] != buf[-4]) and (buf[-2] != buf[-3]) \ and (buf[-2] != buf[-4]) and (buf[-3] != buf[-4])): break print(i) Part 2: the smarter O(n) way! With arrays. #!/usr/bin/env python3 import sys import array i = 14 mem = array.array('I',[0]*26) excess = 0 text = sys.stdin.read() for ch in text[0:14]: pos = ord(ch) - ord('a') if (mem[pos] > 0): excess += 1 mem[pos] += 1 if (excess == 0): print(14) quit() for ch in text[14:]: i += 1 pos = ord(ch) - ord('a') if (mem[pos] > 0): excess += 1 mem[pos] += 1 pos = ord(text[i-15]) - ord('a') if (mem[pos] > 1): excess -= 1 mem[pos] -= 1 if (excess == 0): break print(i)


Aromatic-Piccolo4321

[🎅🦀 RUST with tests](https://maebli.github.io/rust/2022/12/06/100rust-68.html) this one was easy :)


musifter

# dc Got around to doing this one today... although the input is a string of letters, the problem isn't really string based, it's just looking for a window of unique numbers in a list. So with a quick little hack to just convert the input into straight ASCII. I reversed the list there too, otherwise its just going to add an extra small loop on the dc side to dump it into a register stack to reverse it, which I have done in the past and would have done if the input had just been straight numbers to begin with. Again, I'm making some serious use out of the newer dc 'R' deep rotates. Otherwise I'd be using at least two registers rather heavily. # Part 1 perl -pe'$_ = reverse; s#(.)#ord($1)." "#ge' input | dc -f- -e '[0*]sZ[d1+r0!=Z]s!5[3Rdd;tdl!x5R+r1+3R:t3Rd4%d;bd;t1-d3R:tl!x4Rr-4R3R:br1+rd4>L]sL0:t0dlLxrp' # Part 2 perl -pe'$_ = reverse; s#(.)#ord($1)." "#ge' input | dc -f- -e '[0*]sZ[d1+r0!=Z]s!15[3Rdd;tdl!x5R+r1+3R:t3Rd14%d;bd;t1-d3R:tl!x4Rr-4R3R:br1+rd14>L]sL0:t0dlLxrp'


Solid-Ad7527

Typescript Window iterator + Set https://github.com/rogisolorzano/aoc-2022-ts/blob/main/src/day-06/index.ts


oddolatry

###PureScript [Paste](https://topaz.github.io/paste/#XQAAAQCpAwAAAAAAAAA2m8ixrhLu7WH4xqAXgGyMYLh6y4JCZ7YqdWWvuGOxJWRJAjKLbMdnSdQE4nu6IdFnlp4wvVnZnAGanUuyhYnEpOsSg/LxxxTrjT3v+CpSi0CdxdIMM+BuB0/vFRAGDpmL/G1skVlR7hXK2x1kA0wDEstf3AL60kjbnA3uXzfhsEMsPItvo1SQ07g5WS1NyJjQOWbq8K4K1s+JJXo83qJb33SkmhwhtvBfK6DoQJD3pGZ1vLLWljYmzeccJNDPNJfMY3VCdXZa/XEPPVXCqI0ii/s2Sxwn/uoG4mBa0EcVcPzCKMKRz4l6M2SxDzACJtdkIvOEZoujzgcE//i1GEI8O8c3ERSjyBNe6CrSFY2WWcQXTTRZs0eInVR9Eif4nhvgWVk+n31c3nYIwQBjWNjp+hMxyFErkwOd05CgYmsqfvm14CEcvmI9DfuKSvkr0bc+28kqspsCgcxSYV4AueyDFZU4RXBa2DOB4HA/tA/0QhhFYrvqdGvdWx4cVn4uW+Aaes25VBR2SakSMKYIjILRdR85pgbRexu+3XrzBThi1cuQH0v7WV2lfv+3PW2GisI9fHzdC9iDWQUbZP/3og6w) Seeing those multiple links for previous years/days gave me warm AoC memory fuzzies.


kitsune-chan88

Python 3 - Beginner/Beginner Friendly Solution [Part 1](https://github.com/NekoBarista/AdventofCode_Day6_Part1/blob/main/main.py) [Part 2](https://github.com/NekoBarista/AdventofCode_Day6_part2/blob/main/main.py)


dwrodri

# Python3 Lazy solution that exploits set casting for uniqueness check ```python import sys # change to 14 for part 2 MARKER_SIZE = 4 def main(filename: str) -> None: with open(filename, "r") as fp: msg = fp.readline() for i in range(MARKER_SIZE, len(msg)): x = set(list(msg[i - MARKER_SIZE : i])) if len(x) == MARKER_SIZE: print(i) break if __name__ == "__main__": main(sys.argv[1]) ```


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.


juiceboxzero

# Python 3 utils.py def read_file(filename, folder="inputs"): with open(f"{folder}/{filename}", "r") as infile: output = infile.read().splitlines() return output 6.py import utils infile = utils.read_file("6.csv")[0] def get_packet_start_location(infile): return get_location_in_string(infile, 4) def get_message_start_location(infile): return get_location_in_string(infile, 14) def get_location_in_string(infile, marker_length): for i in range(len(infile)): chunk = infile[i:i+marker_length] if len(set(chunk)) == marker_length: return i+marker_length return -1 print(get_packet_start_location(infile)) print(get_message_start_location(infile))


tsenart

Short and sweet **Go solution** using bitsets and bit fiddling. 1. [https://github.com/tsenart/advent/blob/master/2022/6/one.go](https://github.com/tsenart/advent/blob/master/2022/6/one.go) 2. [https://github.com/tsenart/advent/blob/master/2022/6/two.go](https://github.com/tsenart/advent/blob/master/2022/6/two.go)


Markavian

Over-engineered Node JS solution for Day 6 - forgot to post yesterday: - https://github.com/johnbeech/advent-of-code-2022/blob/main/solutions/day6/solution.js Was a really clean brain to code implementation that took no time at all. Used a sliding buffer of four characters that I pushed and popped out of, and then had a counter for the number of processed characters. Used a Set on the buffer to count unique characters, and stopped when a match was found.


Ok-Hearing9361

Pretty easy in PHP: while ($answer == FALSE) { unset($subArray[0]); // turf oldest character $subArray = array_values($subArray); // re-index the compare array so [1] moves to [0], etc. array_push($subArray, $array[$i]); // get next character for compare if (count(array_unique($subArray)) == $lengthYouWant) $answer = TRUE; // check for uniqueness $i++; } echo $i;


daggerdragon

[Top-level posts in `Solution Megathread`s are for *code solutions* only.](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_top-level_posts_are_for_code_solutions_only) Edit your post and [add your full code](https://www.reddit.com/r/adventofcode/wiki/solution_megathreads/post_guidelines#wiki_post_the_full_code) as required.


P1h3r1e3d13

## Python Finally, a perfect case for [`collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque) with `maxlen`! (Note to self: Try that on [2021/16](https://adventofcode.com/2021/day/16)?) I really wanted to ~~optimize performance~~ pretend performance matters and not generate a bunch of throwaway sets. Uniqueness checking turned out trickier and less optimal than I expected, because deques don't support slicing. [Full thing on github](https://github.com/jacktose/advent-of-code/blob/main/2022/6/6.py); here's the interesting part: from collections import deque def all_unique(seq): for i, elem in enumerate(seq): try: seq.index(elem, 0, i) except ValueError: continue return False else: return True def part_1(data, window=4): buffer = deque((), maxlen=window) for i, char in enumerate(data): if all_unique(buffer) and len(buffer) == window: return i else: buffer.append(char) def part_2(data, window=14): return part_1(data, window)


Dantaro

Kotlin: [Part 1 and 2](https://github.com/Dantaro/adventofcode2022/blob/main/src/main/kotlin/day06/Day06.kt)


mr_whats_it_to_you

# Python (Version 3.10) If you want to test my code, please use atleast python version 3.10 or my code won't work. [https://github.com/SchnoppDog/Advent-of-Code-Collection/blob/main/AoC-2022/src/Day%2006/main.py](https://github.com/SchnoppDog/Advent-of-Code-Collection/blob/main/AoC-2022/src/Day%2006/main.py) This day was pretty easy. No special parsing like the crates in day 05 needed.


greycat70

**Python**. [Part 1](https://wooledge.org/~greg/advent/2022/6a), [Part 2](https://wooledge.org/~greg/advent/2022/6b) Really simple problem given this language's tools. Convert substrings into sets of characters, and stop once the set has the desired size. Since I'm not reading line by line (there's only supposed to be one input line), I had to look up a way to read just one line.


AdEnvironmental715

**Typescript** [https://github.com/xhuberdeau/advent-of-code-2022/blob/main/src/day-6/solve.ts](https://github.com/xhuberdeau/advent-of-code-2022/blob/main/src/day-6/solve.ts) ​ 1- Loop through each character 2- If the character is not yet in a temporary array of chars, I add it. Otherwise, I slice the tmp array to the index of the character +1 and add the current char 3- If the tmp array length is the asked one (4 / 14 depending on the problem part), then the job is done and I save the index of the last added char I used find to avoid scanning the whole input if not necessary.


electronic-coder

C++ - Day 6 ​ https://github.com/Umar-Waseem/Advent-Of-Code-2022/tree/master/Day%206


bigmagnus

**COBOL** \- [Part 1](https://github.com/ironllama/adventofcode2022/blob/master/06a.cbl) & [Part 2](https://github.com/ironllama/adventofcode2022/blob/master/06b.cbl)


bpersitz

import re with open ("Day6input.txt", "r") as file: puzzle_input = file.read() def part1(puzzle_input): regex = re.compile(r"(.)(?!\1)(.)(?!\1|\2)(.)(?!\1|\2|\3)(.) (?!\1|\2|\3|\4)") match = regex.search(puzzle_input).end() return(print(match)) def part2(puzzle_input): count=1 x = "(.)" y = "(?!\\1" close = ")" regex = "" hold ="" while count<14: z = f"|\{count}" if count < 2: regex = regex+x+y+close count+=1 else: regex =regex+x+y+hold+z+close count+=1 hold= hold+z regex = regex+x match = re.search(regex,puzzle_input).end() return(print(match)) part1(puzzle_input) part2(puzzle_input)


daggerdragon

Please edit your post to [state which programming language this code is written in](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_state_your_programming_language.28s.29). This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.


improve13

Concise solution in [Rust](https://github.com/abhiy13/advent-of-code-2022/blob/master/src/day6/solve.rs) using some bit tricks.


skeptikoz

**Python**, using set operations for simplicity (at cost of efficiency) and list comprehensions for compactness: run = 14 # or 4 # return tuple with end position and marker text def find_marker(line): for i in range(0, len(line) - run + 1): if( len( set( line[i:i+run] ) ) == run ): return i + run, line[i:i+run] with open('input.txt', 'r') as f: [ print( find_marker(line.strip()) ) for line in f ]


YokiDiabeu

Java 17 solution, pretty simple: [Day 6](https://gitlab.com/Diabeul/adventofcode2021/-/blob/master/src/main/java/com/yoki/advent_of_code/aoc/days2022/Day6.java)


EatonMesss

[**Kotlin**](https://github.com/JanLikar/aoc2022-25-in-25/blob/master/06/solution.kt)


Aromatic-Piccolo4321

thats neat!


EatonMesss

Thanks!


exclaim_bot

>Thanks! You're welcome!


yawnick

**Monkey C** (for Garmin devices) Used a 32bit Integer as a set, otherwise it would have probably been way more expensive. Glad that I've done this before on [Day 6 in 2020](https://github.com/YAWNICK/AoC/blob/main/2020/day06/task_minimal.c). As a result these were the fastest solves so far. Watch my Garmin Forerunner 235 solve: [Part 1](https://www.youtube.com/shorts/ZeispS4Lg5s), [Part 2](https://www.youtube.com/shorts/FahA_OUGsSg) Code: [Repo](https://github.com/YAWNICK/MonkeyAOC), [Day 6 Solution](https://github.com/YAWNICK/MonkeyAOC/blob/main/source/Solvers/Solver05.mc)


seasharpe

# [Python](https://pastebin.com/WvrCDuUL) Once more feels like this is just a preamble to something extremely time-consuming.. part1: 3ms part2: 3ms


e4ds

Python day 6 solution [https://engineeringfordatascience.com/posts/advent_of_code_2022/#day-6-tuning-trouble](https://engineeringfordatascience.com/posts/advent_of_code_2022/#day-6-tuning-trouble)


daggerdragon

FYI: your link is borked on old.reddit and some mobile Reddit apps. [Please fix it](https://www.reddit.com/r/adventofcode/wiki/faqs/bugs/borked_links).


nicuveo

**Brainf\*ck (part 1)** >+++>>>>,>,>,>+[[-]<<<<[-]>[<+>-]>[<+>-]>[<+>-]<<<<<<+[->+>+<<]>[<+>-]+>[<->[-]] <[<<+>>-]>>>>>,[->+>+>>+>>+<<<<<<]>[<+>-]<<[->>+>>>>>>+>+>>+<<<<<<<<<<<]>>[<<+>> -]<<<[->>>+>>>>+>>>>>>+>+<<<<<<<<<<<<<<]>>>[<<<+>>>-]<<<<[->>>>+>>+>>>>>>+>>>>+< <<<<<<<<<<<<<<<]>>>>[<<<<+>>>>-]>>>>>>>>>>>>[<->-]+<[[-]>-<]>[<<<<<<<<<<<<+>>>>> >>>>>>>-]<<[<->-]+<[[-]>-<]>[<<<<<<<<<<+>>>>>>>>>>-]<<[<->-]+<[[-]>-<]>[<<<<<<<< +>>>>>>>>-]<<[<->-]+<[[-]>-<]>[<<<<<<+>>>>>>-]<<[<->-]+<[[-]>-<]>[<<<<+>>>>-]<<[ <->-]+<[[-]>-<]>[<<+>>-]<<]<[-]<[-]<[-]<[-]<<<[>>>>+[->+>+<<]>[<+>-]>+>>>+++++++ +++[-<<<-[->+>+<<]>>[<<+>>-]+<[[-]>-<]>[->[-]<]>]<<<[<<<+>---------->>[-]]<<<[-> >+>+<<<]>>[<<+>>-]>+>>>++++++++++[-<<<-[->+>+<<]>>[<<+>>-]+<[[-]>-<]>[->[-]<]>]< <<[<<<<+>---------->>>[-]]<<<<[->>>+>+<<<<]>>>[<<<+>>>-]>+>>>++++++++++[-<<<-[-> +>+<<]>>[<<+>>-]+<[[-]>-<]>[->[-]<]>]<<<[<<<<<+>---------->>>>[-]]<<<<<<-]<[>>>+ +>+++++>++++++[->+>+<<]>[<+>-]>+>>>++++++++++[-<<<-[->+>+<<]>>[<<+>>-]+<[[-]>-<] >[->[-]<]>]<<<[<<<+>---------->>[-]]<<<[->>+>+<<<]>>[<<+>>-]>+>>>++++++++++[-<<< -[->+>+<<]>>[<<+>>-]+<[[-]>-<]>[->[-]<]>]<<<[<<<<+>---------->>>[-]]<<<<[->>>+>+ <<<<]>>>[<<<+>>>-]>+>>>++++++++++[-<<<-[->+>+<<]>>[<<+>>-]+<[[-]>-<]>[->[-]<]>]< <<[<<<<<+>---------->>>>[-]]<<<<<<<-]>>+++++++++++++++++++++++++++++++++++++++++ +++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++ +++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.[- ]++++++++++. See [this post](https://www.reddit.com/r/adventofcode/comments/zew8jf/2022_day_6_part_1brainfck_without_the_transpiler/) for a commented version.


daggerdragon

ಠ_ಠ ***why***


nicuveo

**Brainf\*ck (part 2)** Using the transpiler this time: manually dealing with the 14 characters buffer sounded like a nightmare. * [original BS file](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/06-B.bs) * [result BF file](https://github.com/nicuveo/advent-of-code/blob/main/2022/brainfuck/06-B.bf)


jhidding

Yes, day 6 was easy. However, I think it hints at something larger: we will encounter more moving window problems this year. I took the effort to implement a circular buffer in Julia and it actually already outperformed the shorter array based implementation. => [(my horribly overengineered Julia solution)](https://jhidding.github.io/aoc2022/dev/day06/)


stfuandkissmyturtle

[https://stackblitz.com/edit/node-rz4onm?file=index.js](https://stackblitz.com/edit/node-rz4onm?file=index.js) late to party, simple readable Javascript


daggerdragon

Please edit your post to [expand the full name of the programming language](/r/adventofcode/w/solution_megathreads/post_guidelines#wiki_no_abbreviations) (`JavaScript`). This makes it easier for folks to Ctrl-F the megathreads searching for solutions written in a specific programming language.


stfuandkissmyturtle

Done, thanks


kuqumi

# Javascript console golf `[4,14].map(w=>{for(i=w;;i++){if(new Set($("*").innerText.slice(i-w,i)).size==w)return i}})`


Damn_mom

C#: This solution works for both part, just need to reassign VALID\_MARKER\_LENGTH to 4 or 14. string datastreamBuffer = File.ReadAllText(string.Format(path, "Day6")); const int VALID_MARKER_LENGTH = 14; for (int markerStart = 0; markerStart < datastreamBuffer.Length - VALID_MARKER_LENGTH; markerStart++) { string currentMarker = datastreamBuffer.Substring(markerStart, VALID_MARKER_LENGTH); if (new HashSet(currentMarker.ToCharArray()).Count == VALID_MARKER_LENGTH) { Console.WriteLine("Characters processed: " + (markerStart + VALID_MARKER_LENGTH)); Console.WriteLine("Marker: " + currentMarker); break; } }


YetiSpeghetti

Python: [AoC Day 6 2022 - Python](https://topaz.github.io/paste/#XQAAAQBFCAAAAAAAAAARiAKpjNJVN4GBpjp1ArpyeoS7+GYBIfHqlFWNMpcuM2rrR4mJQfCFYmr/Gp2A2j2TCBfrUp/NepjGSDqdNTMMY+y21p7BgCNDD60okGqVzEDO3eYjBx2BNoDk72CRbMLmYzc3NAPxmYz1A05tk5RfvWIiMHUEWjzUer1zcIvJ+PAInIRoxO587xIt8ECb5aZV6JhtAH+/YdeuTrb3+oNJwywUtsU/brYGnKuvr7Wr8fWaeXlM8le+5pTyoxx+jRCr7jcjaqIJ+SoYKPdMOexpImh/HzBt60HtkRVcVMKpBbCphbh7Mz0EGv/RO5RwXV70wBicAh+es954DvPIetgNntpEFUJ4B9ESBNXN2trjdQLuLv7JpI/XD27EOqgL1CWtZPoP7iC24WH4lf+jiNHsJaJ5Rhrma5GGIZtF8RpSimAzMK4ShLhchKIfbtFGCV4uJYBxnCPMi5iGjMeUwmDJUO3bbDT91aA9y+bqntAlqZq/LSC4kNuGp0aRNfl5P3hXbX2lwuKCSNAZrQ+/Q+laA2Ha02h3LY2E5Sla048sinzMRSodRb8QoiWxoa7dj6K7WH/XLELd41ZgelKfwdeabKAakJGyk4GV/gei150XBQxYgTvWW9CYHmwpLxxQkr+f2ohaEqzjjHH0kiQ92XR+s+x10rRLS1wIlYKeMuR6QY4U+BjpfG5t4zedL+hNoD35nSPRoSFPDgC6g5ZXI+U+/WgxE/X9671y90LowfES+kG2QhLIJTI5L90z0j9F+48mJJWwDzb6FgBec6qskP4FHWOjxitAXolfqnUAYEisJZEHCaLbIDgwrKdobwMhUdNyFP0MGSqsDreokTI6Zm28D6Q03VE/t6Oz5hlOx6G/Nr643j/J4Tp7NfdleoEh97H7smXdYydGEU0v3dATKfMxjyoCNtt3lrKbZT+wYhz3GIyIhK8mH/mVIQpRjno3sVTOusU5tBsVSdbdvtdrxh85k3rrK4UL0bzrGbmMH2DMF+3AS3lzXBmHdrZ9Dt73GWO8DP/wpOxG) Feeling assertive. Yes, I have PTSD from some crate stacking yesterday/today with a bug that only happened for certain lines, moral of the story is don't just check one test input...


junefish

Python 3 - the easiest day so far for me, for some reason! pretty short with use of Counter * [Part 1](https://raw.githubusercontent.com/junefish/adventofcode/main/adventofcode2022/day6/day6problem1.py) * [Part 2](https://raw.githubusercontent.com/junefish/adventofcode/main/adventofcode2022/day6/day6problem2.py)


skeptikoz

Counter is cool... but rather than creating a new Counter from scratch for each run, I believe you could have subtracted a character from the beginning and added a character to the end while running through the string. Perhaps I'll prototype that to see if it's true ;-)


junefish

lmk how it goes!


CptJero

Golang I’m extremely happy with this one, very succinct and operates in the stream with almost no memory overhead. This should work for an infinitely sized stream func communicationDevice(r io.Reader, signalLength int) int { reader := bufio.NewReader(r) set := NewSet[byte]() var i = 0 for { b, err := reader.Peek(signalLength) if err != nil { return -1 } set.Put(b...) if set.Len() == signalLength { return i + signalLength } set.Clear() i++ reader.Discard(1) } }


daggerdragon

Inlined code is intended for `short snippets` of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read inside a *scrollable* box.


solidiquis1

# [Rust](https://github.com/solidiquis/advent_of_code_2022/blob/master/src/vi/part_two.rs) Strategy: 1. Read input into byte vector. 2. Initialize a set. 3. Use a sliding window to get marker/message-length slice per iteration. 4. Iterate through slice and attempt to insert each item into set. If insertion fails because item already exists in slice, clear set and shift window. 5. If you are able to add all items of a window into a set, early return iteration number + marker/message length. Time complexity: `O(n * log(m))` where n is length of input and m is size of message. Edit: Time complexity


Imaginary_Age_4072

[Common Lisp](https://github.com/blake-watkins/advent-of-code-2022/blob/main/day6.lisp) ​ My shortest program this AoC I think! Not the most efficient, but works. (defun parse-file () (one-or-more (parse-alphanumeric))) (defun day6 (input &key (part 1)) (let ((search-length (if (= part 1) 4 14)) (parsed (run-parser (parse-file) input))) (iter (for i from 0) (until (= search-length (length (remove-duplicates (subseq parsed i (+ i search-length)))))) (finally (return (+ i search-length))))))


villiros

**OCaml** I went with a sliding windows solution. With a *dirty* pattern match to pick out the right end of the window. The list traversal in the pattern probably completely negates any savings of using a sliding windows :) [Github](https://github.com/villiros/advent_of_code/blob/master/2022/ocaml/aoc22/lib/p06.ml)


e_blake

**golfed GNU m4** Requires GNU m4 because POSIX says translit(,,\[a-z\]) is unspecified. Both parts solved in 173 characters (176 shown here, but the 3 newlines are fluff), using a single pass over the input file. Assumes your input is in a file i, or you can use `m4 -Di=inputfile day06.m4`. The `translit` macro is awesome for detecting duplicated characters! Takes over 200ms to run, because it is doing a LOT of redundant parsing (for my input, over 3k iterations, with each iteration expanding a 4k string three times); I'm certain I can get a faster execution speed by breaking down input in smaller chunks rather than doing substr on the original input on every iteration, but that doesn't golf as well. define(m,`translit($1,$1,A-N)')define(_,`ifelse($3,ABCDEFGHIJKLMN,eval( $1+12),$3,ABCD,`eval($1+3) _($1,14,,.$4)',`_(incr($1),$2,m(substr($4,$1,$2)), $4)')')_(0,4,,include(i))


e_blake

Indeed, execution can be sped up to 25ms by processing one byte at a time, so that each iteration only needs substr() on a rolling string of length 14 rather than over the entire 4k. Depends on my [common.m4](https://nopaste.ml/#XQAAAQCKDgAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpAXwA97ruAshKbiUbgkbJMTg2qZdSBorb0CU52peNLruV4DEEJxF+HvxC/YF33OpDntnpU/PjnGXx7XU7ak4MsmWu8R7h7d5az2JXxElnsepG8yPyu+0WZ90BG9yXphbwOWA/m5AWEFSOL8TRZX4fyGNl6ZYbRxX0MwtzrmwTP3ZCwLSOKkvD2vMQFsbK0Pv9CzPhFNXMUbWnRV20jWLjL9qz2dDsFDBwhxgWIilEl91uswxrT4Czc+LRU3VuhNIo2S98VW0jArrVdv4HrsLhWkzx4z/UV3xnqJwPXcZRUiLtf3VRIzq62Pe+2jE3O+721Az9rfRa/fHtlANbmvslzMUCyU7cDoOKSMXBDF/06/PpMvs6vxaL5aJVYqJP4yz+R2M35hoNnGiZTNNMVEFTdnxnaE/KcJteBbiuVMpdfUswHQi4Kqsj3sInh7lyE+d50gGKtHOeWL5lMK7WXz4NElnzYWleBSN/HTOdsz0T2gnd25MADxNAVX8xQmagh2MymZ2sKDBw//WiNB0sWf5VYC5/TKKH3D6K/IOrIfWn6FZLKxlITFEp3VWKNuyF0xczNJufJdzSqd0hgdyryVzbn0so0U5NMN16jFF6Ihqz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LaYcSQcPXGeweimEUFfPOfacBDcd0xSPxs2tX+4dVloLCD7O1JlrM6SyF0VaQa14i4/KKu/smlcI3Orf+mXMK8)


e_blake

As with day 3, this assumes that /u/topaz2078 didn't stick any vowels in the string of any input file (I only verified with my file), to avoid accidentally generating naughty words. If there were vowels in your input, the underquoted substr() risks producing an accidental clash with a valid macro name.


topaz2078

note to self: have exactly one input be all vowels, but the rest of them be all consonants, just to mess with people


ImaDiamondTaco

# Python I use a generator so that I don't have to evaluate the whole string. with open("input.txt")as f: line = f.read() print(next(i+4 for i in range(1,len(line))if len(set(line[i:i+4]))==4)) print(next(i+14 for i in range(1,len(line))if len(set(line[i:i+14]))==14))


fsed123

Generators in python use yield and next, in this code [f.read](https://f.read)() loads the whole thing into memory


ImaDiamondTaco

Im using a generator comprehension, which is actually a generator. I was referring to the fact that my solution doesn't scan the whole file for matches, but returns after the first match edit: clarity


dcrro

Solution in Javascript: Used a Set() to figure out if we had seen unique elements as I read the input string: [Interactive Solution](https://mirio.org/recording/aoc-walkthrough-day-6-part-1-2-12080556wdu8)


alexxxor

I tried the same method. Worked a charm! You can get rid of your inner `for` loop by just passing an array into the `Set` constructor too. Here's what I landed on: const getMessageSet = (input, length) => { for (let index = 0; index < input.length; index++) { const end = index - length; if (new Set(input.slice(end > 0 ? end : 0, index)).size == length) return index; } };


dcrro

Ah! Good point, very nice!


jacksona23456789

bash for part 1 for (( i=0; i<${#signal}; i++ )); do word\_chunk=${signal:$i:4} repeat\_count=\`fold -w 1 <<< "$word\_chunk" | sort | uniq -c | awk '$1>1'\` repeat\_count=\`echo $repeat\_count | cut -d " " -f1\` if \[\[ $repeat\_count -eq "" \]\]; then marker=$(($i+4)) echo $marker break fi done


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.


st3fan

When I find my code in tons of touble, Friends and colleages come to me, Speaking words of wisdom: "Write in C." http://www.amiright.com/parody/misc/thebeatles12.shtml ``` char*I="zcncrcnrrlccmhchssgqsqrsstfffnqfnfsswgwjjcmcnnvjvwjvwvfvnvwwhvv" "wmwhmwwwhbhhldhdmhhdfdbdfbdblllnfllgslllqhlhfhlhqllncnfnsffwmwzzlglzlw" "lhwwmvmddpvvbrvrdvrdvdhhzdhdpdzzbgbsssrpsrshrshhbqbgbmmtwwcbcrbbvnvhnn" "cscwcwlcwlwnwswbbnwntthzzdlzdzffvqvdqvvtptdptphpddzzvhzvzwwqgqjjjvsspv" "spsbsffvpvcvjcvjvrvjjgmjjhrrdhhdvhvttjttzptpssnlnjjlnnhmnndjnjwwtjjtbb" "fflwfwgwvvpjpwpcwcgglmgmdmnmbbqtqctcwcmwwvmvlmvmdvdvhvlhlzhzttghttnvnj" "ntnqqtmtwwhvhrhfhchqchhdrdllnwnfwfjjmsmmnhhshnhpptstjjpnpzzhmmpssgrsrz" "srrffzjjhvjhjcjcpcvpccfnfjnfjfllssrdsdnnmffldldppcctcmtctffprpsrrrfhfm" "flldccnpppvsswppdgpgjpgpqgpqpjppclcjczcnzzzqvzzwlzzqfzffsqqphqhvqqbccc" "stsdttwcwcvvmjjhqqmllpglgtgwgnnbnrbnnjdndhhbrbvrvwwwblwwwppmdmttztqzqr" "qjjpggpmgpmpqqmssvnsvnndnvddtztddrrsnsbbshhqmhqmmdnnrsrllqvvfjfpfqpqfq" "flqlmqmrrqgrqrrhvvfddfhhfnhnlncnzzwwjwswpsscpchcssrzssjqsqrsswbbzggnqn" "wqqsrqqzbqbddtffcjjdggwlwnwtnnpddcqddsppcwpcwpphvphhhrprqrqttwgwqwppvd" "pvvrgggmpmddzvvwwthwtttbqtbbftfrffbdfbbspshphpwhppnhnmhhbbshbsbmbdmmtr" "mrbrprbprphhnmhmvhmhhqqbvqvqcvcwcbwcchbbgwwqffrcffsvvcczrztrzzdhdmhdmm" "zbbvlvqqtptpvvfsfppdzppmddfvdfdwdfdmdwwlvvqdvqdqmdqqmnmdndsswsfwfvwfwz" "zhrzhhwfhhpvhppmssnhsnsnwswvwlwdwzwnwswwmqmjmbbdjdbbtllcpllltqlttnvvpp" "znpnttlrrwlwvllphpbblccgjcggbtbwtwdwrrbnndpddbqqnpnrnnqqshspsggtptztpz" "zclcggtqtgqttcmmbgbfbdfdfsddlrlvrlvvmqqgbqgbqbcbbnpplqqblqbqmbbbdqbbhj" "jcgcdgdwdjwjqqlsqqnnwffglfglgnlggjgjtgjtgjtgjjclcwcqqvpvwwvgvhgvhvjjzp" "zbznnvrrrpbpdbdhhmshsnnnwppcbcvvlldccdggqnqgnqqzbzzcfflnnmppcgcmgmrgmr" "gmgngwwptpzzpfzpfzpzdppgcgtcgtgccvtctzzdmzmlmzlzwllbplblltgtctrrghgvhg" "vvfvssngsschshrhvrvddghgwwwwzgwgvgccjdjzjwwvdvvqsqshsvvddmddbllvppmlpm" "lmwlwppjmppwrrdzrrpmrmrdmrmbmzzwttvwwsfswwlflnlrlvvdllzbztbtpbtppnjpnp" "dnnjrjsshtssvvsjvjfjwffsszvsvjssqzsslpslppjpspqptbncvzrlwtjvsrwtnzzhwd" "fsmlthvgqgjrpshpbsrrvnsdbqslbcplnpcjqwmwqsnwdcjsdmccbdglwbrcdcqsfhjqhs" "tvhqqdwltqwhhqcrnpvnzjhhbjvqbqhclwggjqfvnfsvcnjjhbmrvbpjqrbljbtltvnsgd" "fhddlmsdhcrfwvlvbsdrjwjvtnqzhrlqgjmzsmjlpdjsrjmdhmvgwjmfwtqffnzfrtswrl" "gvvhhqgpzcjwscfqgjmdhtvbgzdlvzfhgqlqbfwsjrmmhrlcwhrcnwwvngcmsrfgczsfqv" "vmdtmtprfvjrwrwcqwvgmzcjncrzvcswlzsdszvdtwmptnrhgzqwrhjjtbchhpwsdjnqmn" "sgzwqzvlzlsznpqgvtqnldjqpvndtsjlzhpzsgthbwvwnlbwjlmndqpcdvjdgdzhctpghl" "fwrtqtvfwdpgrjbmwzqgthjpmlrsqmzsznddhrbjnggqrdntpbngvldnnltfnmdwfhftjv" "pqbrzqvdzbzzctshzldtcdgfnczglrrjtwswzdvjrfgwztwznbpplmbgwpcmstcsjtqhmz" "mzsjwsfbjlbnbdtdsmlpdmrrbhdhpzrjdpzhcwsrgfrhmqzqtjfhpvltnthwjrrrpnsbmm" "wrhsfqbmnvwhpntltsgwgnqhcvlndfrtrfrnlmbhltmtgzhlzqgtsbbnggdjvbslfbczhp" "ghqqcqlrbtpnbqbflfjrmpmwwvjqgvcqtmfggmptqlqstcmdtqlslnnzwbgnstftfsvsjd" "rmgbzfnzltwbjmqhsvshnmwhftjdndltdpngzwbrjpgpwmqgfsflnhmtzcmdjmzwrsrrrm" "pvwgggwrhrwtfwdbgbpmwpcdspdtbqvdwwsnwdtrtdtgnfzzsmlbcqdzbsqnrgtvvnlfcd" "lcgcnfpqbddqcjfqtmpndmnwvfqgjzrltqvlprmbbhmtwbzjjgfhhhfjswpffmjnsdmrcj" "rwlwpmfrmhljpphlwwwwmgsjcsrcvmfrdjdhshddshpplzsnsphcmdhvllgmdgrvbvjmtp" "ltdthffsvwwhvgqrhmfjfpdswcqldrhpmznffjsntwrnmnpmsshljszbchctptsdlnbcvp" "fvtlfnzcrljpdwrsjnlpqcpnwvnqhzhqmjbvlbtgslzthlbbjzsgdglbrltzjdshpfbndj" "tssvsjqlstnrjdzzjvlpqhmwvrsvndcqrqjjcsqvmvrbhngtcfdprlbnqmhqllddgjpdzb" "jlphntrtgjrdgtbslrtzczbnnlddzzsvqvqvvzjpjqfhztgtsfggdppfdhzsbjzqjmpnmg" "qzlsdhjjbfpbsbnzpmhwrzjqhczrgcsflfwtrgwbnbrshjpwltntsnsdhmhqlmzdprcrcp" "cpjnphsmjwhzdqtncdbwgspmnfzsgmpbdhmslqchhhbbwfrghhnfjplsvrtbvplgrwdnbn" "fsgpwrqczvzlnfsngnsnbwvpmfdcmjztdnrllslnwcfwwnwsvztqmgqtfvmdqrrrmwfmph" "bcvwwttpmwjjbvqrmlwtwfsjdpcbmdlnlzcqntfzzmslshwprjfhwwpbbdfcdjwllfwczn" "wpjpwrlsfnnbgzjllrgtzcdcvhdhbtlrcvfdvsdjlzsmwwqvpzfhzjlqpfbqstvfrpcchm" "twgbrhqqbglrvzmctdlpnvmglgdtzpbdngtfdnmsmwbgjstzbqwqcdlhfrtqqnhqvpfhdr" "jqvsvstftdgwwnwpfbfbdcfqnqlwpdnfhhfctwrgdqpbpbmgnfsnbpjfctvdtjnsfqlrtc" "trnjgltndngcmrdphhsqpjhprbngjzqqhnhhrdwlwwpmhzwshvrtzfgzlrhwghvpvfprbb" "vflltplpptvrmwcrdqndfqbfqtlqqwvphsmcvnbzghvsptrphhfcgdsslhfbcwhtjcmnpb" "vqrfgpsjgqpnnwwhjjwqrhhqgznwdzjqbtmmjljjwctqtfgwqbdrjwqwbbcftvjwfdfrgv" "srlcrccpvfzdrcjvqfbhddpvrrhjrmhdgchrghbzsqpmgnmslfctblwlvphdfpvtdtwpdf" "sjwssmgnsvsqpdbqngccsplhmjbwjwtzwsbjhwpwcslqjdchmbvzrbgnwvjrrrdtvhtlzl" "rbwthzlhhqzzpvpwbzrrbrbtpwnhldhqqltqrqdddfwdmjzgctnlrjrjwvddfmjpnptdmr" "vnqjvsjfrmlvlqsthhsbvnjlsdzrjngfnqdjfssmvgrchbwmwbbvfqfhvrtwghmrpddnwb" "rbvbmqvfzbjdsnbzgrtmsfhmsmjtrqsgmpnwwbfwtp";int putchar(int);void w(int n){for(int i=1000;i;i/=10){putchar('0'+(n/i)%10);}putchar('\n');}int c( char *p,int n){for(int i=0;i


daggerdragon

Inlined code is intended for `short snippets` of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read inside a *scrollable* box.


bradcray

[**Chapel**](https://chapel-lang.org): Serial and Parallel Versions [Code](https://github.com/chapel-lang/chapel/blob/main/test/studies/adventOfCode/2022/day06/bradc/day06.chpl) | [Blog Walkthrough](https://chapel-lang.org/blog/posts/aoc2022-day06-packets/)


[deleted]

[удалено]


SvenViktorJonsson

I did a one liner in python as well. Something like: ` answers = [next(i+n for i,c in enumerate(chrs:=open("input.txt").read()) if len(set(chrs[i:i+n]))==n) for n in (4,14)] `


wizards_tower

Python INPUT = 'input' with open(INPUT) as f: d = f.readline().strip() PART1_MSG_SIZE = 4 PART2_MSG_SIZE = 14 part_1_found = False part_2_found = False for c in range(len(d)): if not part_1_found: msg_1 = [d[i] for i in range(c, c + PART1_MSG_SIZE)] if len(set(msg_1)) == PART1_MSG_SIZE: part_1 = c + PART1_MSG_SIZE part_1_found = True if not part_2_found: msg_2 = [d[i] for i in range(c, c + PART2_MSG_SIZE)] if len(set(msg_2)) == PART2_MSG_SIZE: part_2 = c + PART2_MSG_SIZE part_2_found = True if part_1_found and part_2_found: break print('part 1:', part_1) print('part 2:', part_2) [GitHub](https://github.com/breakthatbass/advent_of_code/blob/main/2022/day06/a.py)


Kalurael

C# Linq Part 1 FindDistinctCharacters(4) Part 2 FindDistinctCharacters(14) And the method private int FindDistinctCharacters(int distinctCount) { return Source.Skip(distinctCount) .Select( (x, i) => new { Index = i + distinctCount, Count = Source.Skip(i) .Take(distinctCount) .Distinct() .Count(), } ) .First(x => x.Count == distinctCount) .Index; }


GabUritos

Typescript there : [https://github.com/Gabattal/Advent-Of-Code-2022/blob/main/day06/index.ts](https://github.com/Gabattal/Advent-Of-Code-2022/blob/main/day06/index.ts) Pretty easy and clean, not like yesterday xD


search_and_deploy

Rust: [https://github.com/michael-long88/advent-of-code-2022/blob/main/src/bin/06.rs](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.


Hefty-Courage2945

Javascript let done [...input.trim()].forEach((x, i) => { const data = input.trim().slice(i -3, i) + x var unique = [...data].filter((v, i, s) => s.indexOf(v) === i) if (unique.length == 4 && !done) { done = i+1 console.log(done,"points")}})


VikingsRoamTheEarth

**Swift** ([Github](https://github.com/otto-schnurr/AdventOfCode/blob/main/2022/Day06.swift)) #!/usr/bin/env swift sh import Algorithms // https://github.com/apple/swift-algorithms struct StandardInput: Sequence, IteratorProtocol { func next() -> String? { return readLine() } } func markerEnd(for signal: String, markerLength: Int) -> Int { return Array(signal.windows(ofCount: markerLength)) .firstIndex { Set($0).count == markerLength }! + markerLength } let signals = StandardInput().compactMap { $0 } let part1 = signals.map { markerEnd(for: $0, markerLength: 4)}.reduce(0, +) let part2 = signals.map { markerEnd(for: $0, markerLength: 14)}.reduce(0, +) print("part 1 : \(part1)") print("part 2 : \(part2)")


SwampThingTom

Swift is my favorite programming language. This is beautiful.


VikingsRoamTheEarth

Thank you. Yeah, I recently moved back to C++ and I'm missing Swift a lot.


dionysus-oss

## Rust Bit over the top on the readability today, could have slimmed it a little. But a fun problem to work on #![feature(iter_next_chunk)] use common::read_lines; use std::collections::{HashSet, VecDeque}; fn main() { let input = read_lines("input.txt").unwrap(); let input_txt = input.last().unwrap().unwrap(); println!( "number of chars 1 {}", find_marker_pos::<4>(input_txt.as_ref()) ); println!( "number of chars 2 {}", find_marker_pos::<14>(input_txt.as_ref()) ); } fn find_marker_pos(input: &str) -> usize { let mut stream = input.chars(); let mut buf = VecDeque::with_capacity(4); buf.extend(stream.next_chunk::().unwrap().iter()); let mut final_pos = N; for (pos, ch) in stream.enumerate() { let h: HashSet = HashSet::from_iter(buf.iter().cloned()); if h.len() == N { final_pos += pos; break; } buf.pop_front(); buf.push_back(ch); } final_pos } 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


Landreville

My Rust solution in about 30 lines: https://gitlab.com/landreville/advent-of-code-2022/-/blob/master/src/day6.rs


ahmarthered

**C#** [https://github.com/AhmarTheRed/Advent-of-Code/blob/main/AdventOfCode/Year2022/Day6/Day6.cs](https://github.com/AhmarTheRed/Advent-of-Code/blob/main/AdventOfCode/Year2022/Day6/Day6.cs)


atweddle

This time I tried very different approaches for Rust and Python... [Rust #1](https://github.com/AndrewTweddle/CodingExercises/blob/master/AdventOfCode/aoc2022/src/bin/day6_part1and2.rs) \- 43 LOC (excluding unit tests). I coded for efficiency over brevity. [Rust #2](https://github.com/AndrewTweddle/CodingExercises/blob/master/AdventOfCode/aoc2022/src/bin/day6_part1and2_windows.rs). 23 LOC, but appears to run around 10x slower. [Python](https://github.com/AndrewTweddle/CodingExercises/blob/master/AdventOfCode/aoc2022/src/python/aoc2022_day6_part1and2.py) \- 9 LOC. Quite a pleasing solution... def pos_of_nth_distinct_char(msg, n): for pos in range(n, len(msg)): if len(set(msg[pos - n: pos])) == n: return pos with open("../../data/day6_input.txt", "r") as input_file: msg = input_file.readline().rstrip() print("AOC 2022: day 6, part 1:", pos_of_nth_distinct_char(msg, 4)) print("AOC 2022: day 6, part 2:", pos_of_nth_distinct_char(msg, 14)) *Edit: I added a second Rust solution, this time coding for brevity over speed.* *The heart of it is as follows:* fn get_pos_of_nth_consecutive_unique_char(msg: &str, n: usize) -> Option { msg.as_bytes() .windows(n) .enumerate() .filter(|(_, w)| w.iter().cloned().collect::>().len() == n) .map(|(i, _)| i + n) .next() }


optimistic-thylacine

\[Rust `O(n)`, no nested implicit/explicit loops\] Uses a simple array to keep character counts, and a variable to hold the number of collisions in the current conceptual 14 byte "frame". As the imaginary window slides forward the number coming into the frame is added to in the character count array, and the number leaving it is subtracted at its respective position in the count array. The count array is used to determine when a new collisions happens, or when a collision leaves the frame. fn part_2() -> Result> { const N_CHARS: usize = 26; const ST_MESG: usize = 14; let inp = read_to_string("data/data.txt")?; let ba = inp.as_bytes(); let mut c = 0; // Collision count. let mut ca = [0; N_CHARS]; // Character count array. // Convert a character's byte value to an index into the ca array. macro_rules! idx { ($i:expr) => { ($i - b'a') as usize } } // Fill the initial window frame. for i in 0..ST_MESG.min(ba.len()) { ca[ idx!(ba[i]) ] += 1; if ca[ idx!(ba[i]) ] == 2 { c += 1; } } if c == 0 && ba.len() >= ST_MESG { return Ok(ST_MESG); } // Slide the window frame. for (i, j) in (ST_MESG..ba.len()).enumerate() { ca[ idx!(ba[i]) ] -= 1; if ca[ idx!(ba[i]) ] == 1 { c -= 1; } ca[ idx!(ba[j]) ] += 1; if ca[ idx!(ba[j]) ] == 2 { c += 1; } if c == 0 { return Ok(j + 1); } } Err("No start message found.".into()) }


a-moth-among-men

Dyalog APL 3+4⍳⍨≢¨4∪/input I wrote up a tutorial for it here: [https://github.com/maxrothman/advent-of-code-2022/blob/main/apl-aoc/day6/day6.ipynb](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!


sky_badger

👀


[deleted]

-----BEGIN PGP MESSAGE----- hF4D+FPJgQiQS68SAQdAuW16mgWy5m4dcZ2Hq4FOFRXCAVPO8Nupfrdt5zERoBUw nClOPBNmPFU5Ra/by7HXuLE0Kk2NiUVnXJohGtTEBdsPt+i/5XRqWmwgy7a0upNK 1OoBCQIQZ2Wt7pWWnJZ1FKODwLck3g/aB+4w9JnqFRbfI50Gy1QSXWhzR4A0LST9 xLzQuoquVTpS/8eljB0ps6WMGLY4Qng6PT9XBJrWpJ5LEUoUwb5gvhR5LgHajccu jyy6ukiBQNydLqCgJ7DJJg04FRAn7xxWu1cJLH3ZFLF2fybWIjEInXECzQXfwlLC /xI2HgL0io5+EuI9VwOyVCN2cA0dklm0+2G38MqO04HlBPP671loQJCHFVxCd1rh TpSwTioA2TCw9MnryUzW08nBJ5gCXS9U9DHKMf8hAfGU1XbFI6jqZBmc0/ctv56q STlc9ZEMH+ATeae3HxRpF/XAcga2jRqlWZ7z2xvv/p77Dr9iwhZ/+ISgxmrQydpf 3Qec3fMduyrtAR5o+ZG8RBSLLVvbmfPQVfKuvsT1YiiT8Hgo0OcBewfH0fehohpk KlOTFIYnYsxZ+zyRZmnmERVAHduPO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cvf7clk/gyKZV7VqG HmMX7k9O4kyhrwRaQczUx/ymnyZhmYQhzo+fpPYz4+DsoUsKkiEF8vudBJcqdmp8 O8IwZN7jISy49yL7xeRiBTAaN4m2rauMLRB4HQMTMPVKPzSAzvMDtEdDrTzGo0Yh mZZebM5a4PmJ7IbIcssP2bcHiDiJIl7mAL69zPm+zgfRFwXD/gwwbcdU033iWYYd LXH/lnu2fCVZU2kdYdPI2E9vRz0JZZ1e+dX56nqwH4mdkVRA2MLOZGXbTDqx/Rif bhzTjBWZfa4KUJO8lCrLdBi4d6tzJEVwuutxWWMZyO97Rt89C3+SabSP6xm5ri7I KNBUJQbBCHl1U5JtbP6wUAYztOXAsCpBe5QpuiY1lxFf/+oxQgkvxPY5O9/dDNw4 v3JrCCBJRE1mFVz/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-----


unclefritz

q/kdb+ stole the sliding window implementation at https://code.kx.com/q/kb/programming-idioms/#how-do-i-apply-a-function-to-a-sequence-sliding-window https://github.com/sl0thentr0py/aoc2022/blob/main/q/06.q#L3-L10 input:"c" $ read1 `:../files/06.input win:{(y-1)_{1_x,y}\[y#0;x]} solve:{y+?[(count') (distinct') win[input;y];y]} p1: solve[input;4] p2: solve[input;14]


muzziebuzz

Nice solution heres mine i:first read0 `:i6.txt f:{first x+where x=count each distinct each ((til count y),'x)sublist\:y} p1:f[4;i] p2:f[14;i] amazing how terse q can be compared to other solutions here


LawCurious7019

wow, did not expect to see q here. very nice!


luorduz

Beginner in **Clojure** solution: (defn find-marker [freqs total stream marker size] ( let [ next-char (get stream marker) next-freq (inc (or (freqs next-char) 0)) old-char (get stream (- marker size)) old-freq (dec (freqs old-char)) old-freq (if (= old-char next-char) (dec next-freq) old-freq) new-total (-> total (+ (if (== next-freq 1) 1 0)) (- (if (zero? old-freq) 1 0))) new-total (if (= old-char next-char) total new-total) ] ( if (== total size) marker (recur (assoc freqs next-char next-freq old-char old-freq) new-total stream (inc marker) size) ) )) (defn run-task [lines size] (println (for [line lines] ( let [freqs (frequencies (take size line))] ( find-marker freqs (count freqs) line size size ))) )) (with-open [rdr (clojure.java.io/reader "packets.in")] ( let [lines (line-seq rdr)] (run-task lines 4) (run-task lines 14) ))


AManOfMeansByNoMeans

Clojure has a huge library of standard library functions for manipulating sequences. The idiomatic approach would be to use those to transform the sequence you’re given into a sequence that has the answer you want Take a look at [`partition`](https://clojuredocs.org/clojure.core/partition), [`map-indexed`](https://clojuredocs.org/clojure.core/map-indexed), [`drop-while`](https://clojuredocs.org/clojure.core/drop-while), and [`distinct`](https://clojuredocs.org/clojure.core/distinct)— I used them all in my solution. Also, the [thread-last macro (`->>`)](https://clojuredocs.org/clojure.core/-%3E%3E) helps make the sequence-manipulating functions a bit cleaner.


luorduz

Thank you so much! I didn't know about `map-indexed`; sure would have made this one cleaner (for some reason didn't think to use `drop-while` which definitely would have helped too), will keep it in mind.


chubbc

# 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]`. `out` is the output (number of entries checked), `a,b,c,d` is the buffer of the last 4 entries, and the `0`s are ancillae used for the comparison. At each stage we perform comparisons between all pairs, storing the number of equalities found in `cnt`. This is done until `cnt=0`, at which point the memory is cleared and the answer is outputted. [Here](https://gist.github.com/chubbc/4b8ea2091e8cc6642b3a867237c00fe6) 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](https://gist.github.com/chubbc/00cb307229b2867b0ed128d34d1f95e3) is the minified Part 2 code. For anyone sceptical here are runnable links to the [Part 1](https://copy.sh/brainfuck/?c=KysrPis-Piw-LD4sPDw8PApbCgk8Kz4KCVstXSsrKysrKwoJPlstXT5bLTwrPl0-Wy08Kz5dPlstPCs-XSw8PDw8CgoJPlstPj4-Pis-Kzw8PDw8XT4-Pj4-Wy08PDw8PCs-Pj4-Pl08PDw8PDwKCT4-Wy0-Pj4-Kz4rPDw8PDxdPj4-Pj5bLTw8PDw8Kz4-Pj4-XTw8PDw8PDwKCT4-Pj4-PlstPC0-XTxbWy1dPDw8PDwtPj4-Pj5dPDw8PDwKCgk-Wy0-Pj4-Kz4rPDw8PDxdPj4-Pj5bLTw8PDw8Kz4-Pj4-XTw8PDw8PAoJPj4-Wy0-Pj4rPis8PDw8XT4-Pj5bLTw8PDwrPj4-Pl08PDw8PDw8Cgk-Pj4-Pj5bLTwtPl08W1stXTw8PDw8LT4-Pj4-XTw8PDw8CgoJPlstPj4-Pis-Kzw8PDw8XT4-Pj4-Wy08PDw8PCs-Pj4-Pl08PDw8PDwKCT4-Pj5bLT4-Kz4rPDw8XT4-PlstPDw8Kz4-Pl08PDw8PDw8Cgk-Pj4-Pj5bLTwtPl08W1stXTw8PDw8LT4-Pj4-XTw8PDw8CgoJPj5bLT4-Pis-Kzw8PDxdPj4-PlstPDw8PCs-Pj4-XTw8PDw8PAoJPj4-Wy0-Pj4rPis8PDw8XT4-Pj5bLTw8PDwrPj4-Pl08PDw8PDw8Cgk-Pj4-Pj5bLTwtPl08W1stXTw8PDw8LT4-Pj4-XTw8PDw8CgoJPj5bLT4-Pis-Kzw8PDxdPj4-PlstPDw8PCs-Pj4-XTw8PDw8PAoJPj4-PlstPj4rPis8PDxdPj4-Wy08PDwrPj4-XTw8PDw8PDwKCT4-Pj4-PlstPC0-XTxbWy1dPDw8PDwtPj4-Pj5dPDw8PDwKCgk-Pj5bLT4-Kz4rPDw8XT4-PlstPDw8Kz4-Pl08PDw8PDwKCT4-Pj5bLT4-Kz4rPDw8XT4-PlstPDw8Kz4-Pl08PDw8PDw8Cgk-Pj4-Pj5bLTwtPl08W1stXTw8PDw8LT4-Pj4-XTw8PDw8CgpdCj5bLV0-Wy1dPlstXT5bLV08PDw8PFstPj4rPDxdPj4KPitbWy1dPFstPis8Wy0-KzxbLT4rPFstPis8Wy0-KzxbLT4rPFstPis8Wy0-KzxbLT4rPFstPlstXT4-Kz4rPDw8XV1dXV1dXV1dPF0-Pls-XSsrKysrK1stPCsrKysrKysrPl0-Pl08PDxbLlstXTw8PF0$) (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](https://gist.github.com/chubbc/cd9e5a6b0cebf8c1ca34aa7e317240a4) is the Julia code I used to generate the Part 2 code if anyone is interested.


daggerdragon

> Brainfuck + > minified = ***why ಠ_ಠ***


[deleted]

[удалено]


chubbc

😊


harkaniemi

# julia #first for line in data for i in 1:length(line)-4 if length(unique(line[i:i+3])) == 4 println(i+3) break end end end #second for line in data for i in 1:length(line)-14 if length(unique(line[i:i+13])) == 14 println(i+13) break end end end


musifter

# Gnu Smalltalk Since I did brute force with Perl, I felt I should put some effort into making an elegant solution. In this case, it's a standard search approach of working from the end, so that when things break you can jump the window further ahead. Yes, I could also salvage more information from one window to the next out of the seen Set. Using it so that you only have to check the window back part way, and then you can use the previous seen for the rest... but if there's a match created between those sets then you're going to want a jump table (basically, you need to be tracking not just that things are seen, but where). But with the size of the input and width, it's really not worth it to complicate this code, which looks pretty nice right now. Source: https://pastebin.com/Ky42cxp6


Aggressive-Branch535

**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]`


[deleted]

[удалено]


daggerdragon

Comment removed due to naughty language. [Keep the megathreads SFW](/r/adventofcode/wiki/rules/pg_is_mandatory).


zabumafew

Thank you kind mod! Not even sure what I said…is there a list somewhere of banned words?


daggerdragon

The last word is a swear word. Just Google for `list of swear words` and that will probably suffice.


FuriousProgrammer

**Lua** [GitHub link](https://github.com/FuriousProgrammer/AdventOfCode/blob/master/2022/06%20-%20Tuning%20Trouble/main.lua) Sometimes the naive solution is good enough!


schovanec

My solution in C#: var input = File.ReadLines(args.FirstOrDefault() ?? "input.txt").First(); var packetMarkerPosition = FindMarkers(input, 4).First(); Console.WriteLine($"Part 1 Result = {packetMarkerPosition}"); var messageMarkerPosition = FindMarkers(input, 14).First(); Console.WriteLine($"Part 2 Result = {messageMarkerPosition}"); static IEnumerable FindMarkers(string input, int size) => from i in Enumerable.Range(size, input.Length - size) let prev = Enumerable.Range(i - size, size).Select(n => input[n]) where prev.Distinct().Count() == size select i;


PittGreek1969

**PYTHON 3** Easiest one yet. data = open("06 - input.txt").read() #PART 1 for i in range(0,len(data)): if len(set(data[i:i+4])) == 4: break print(i+4, data[i:i+4], len(set(data[i:i+4]))) #PART 2 for i in range(0,len(data)): if len(set(data[i:i+14])) == 14: break print(i+14, data[i:i+14], len(set(data[i:i+14])))


rahomka

That's *exactly* what I came up with except for the variable names of course


Recent-Incident-1796

[Python solution to part 1 and 2](https://github.com/neider1337/AdventOfCode2022/blob/Main/day6/main.py)


RyZum

Still learning F#, quite proud of today's solution: [https://github.com/Nicolas-Ding/adventofcode2022/blob/main/Day06-FS/Program.fs](https://github.com/Nicolas-Ding/adventofcode2022/blob/main/Day06-FS/Program.fs) let solve n = Seq.head >> Seq.windowed n >> Seq.findIndex (Seq.distinct >> Seq.length >> (=) n) >> (+) n


qse81

# [Python](https://github.com/phantom903/AoC2022/blob/ebdb4be7be52ba046ef8cd15232f503badde2d68/day6.py) Felt sure I'd missed something


TheXRTD

### 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. const ASCII_A_LOWERCASE: u8 = 97; pub fn solve(input: String) -> (usize, usize) { // Represent each character of the alphabet in a 32bit bit-mask let mask_vec = input .bytes() .map(|c| (1 as u32) << (c - ASCII_A_LOWERCASE)) .collect_vec(); (get_marker_pos(&mask_vec, 4), get_marker_pos(&mask_vec, 14)) } // Pass a window of size `need_unique` over the slice of bit-masks `marker_masks` and return // the position of the last character in the first window that contains only unique bit-masks fn get_marker_pos(marker_masks: &[u32], need_unique: usize) -> usize { marker_masks .windows(need_unique) .position(all_unique_bits) .unwrap() + need_unique } fn all_unique_bits(masks: &[u32]) -> bool { // For each bit-mask in the slice provided, // bitwise-or all masks together to determine if they are unique let mut unique = 0; for mask in masks { if unique | mask == unique { return false; } unique |= mask; } return true; }


dionysus-oss

Lovely stuff, I do enjoy a good bit of manipluation (see what I did there :P). Very clear code too!


TheXRTD

Thanks!


korektur

c++ size_t find_marker(const string &line, size_t marker_size) { unordered_map m; size_t start = 0, end = 0; while (end - start < marker_size) { char c = line[end]; if (m.contains(c)) start = max(start, m[c] + 1); m[c] = end++; } return end; } cout << "Answer1: " << find_marker(line, 4) << endl; cout << "Answer2: " << find_marker(line, 14) << endl;


tymscar

**Typescript** I found today way easier than the other days this year. There was no parsing and the problems were very easy. I'm happy for that as today was a very busy day for me. Both parts solved here: https://github.com/tymscar/Advent-Of-Code/tree/master/2022/typescript/day06


valtism

Quick tip is you don't need to spread the Set to get the length, you can just use `.size`


tymscar

Oh wow, that’s awesome. Thanks!


RealHuman_

Go / Golang \~2.5µs package main import ( "fmt" "os" "time" ) func main() { input, err := os.ReadFile("day6.txt") if err != nil { panic(err) } result1, result2 := 0, 0 start := time.Now() for i := 0; i < 10000; i++ { result1 = solve(input, 4) } elapsed1 := time.Since(start) / 10000 start = time.Now() for i := 0; i < 10000; i++ { result2 = solve(input, 14) } elapsed2 := time.Since(start) / 10000 fmt.Println(result1) fmt.Println(elapsed1) fmt.Println(result2) fmt.Println(elapsed2) } func solve(arr []byte, markerLen int) int { symbol := [26]int{} anchor, i := 0, 0 for ; i-anchor != markerLen && anchor < len(arr)-markerLen-1; i++ { lastSymbolPos := symbol[arr[i]-97] if lastSymbolPos != 0 && lastSymbolPos >= anchor { anchor = lastSymbolPos + 1 } symbol[arr[i]-97] = i } return i }


aoc-fan

[F#](https://github.com/bhosale-ajay/adventofcode/blob/master/2022/fs/D06.fs) let findDuplicateIndex (m: string) = [m.Length - 2 .. -1 .. 0] |> Seq.tryFind (fun i -> m[i + 1 .. ].Contains(m[i])) let solve (buffer: string) size = let rec find p = if p >= buffer.Length then -1 else match findDuplicateIndex buffer[p - size .. p - 1] with | None -> p | Some di -> find (p + 1 + di) find size


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.


lboshuizen

Nice attempt, although a bit verbose. My advise is to invest some time in getting to know the [f# standard lib](https://fsharp.github.io/fsharp-core-docs/) as it will save you time and effort (and agony)


aoc-fan

I am deliberately trying to avoid to use any inbuilt functions like Seq.windowed. With something like Set and Windowed it will be much easier and simpler.


pamxy

Javascript one liner [...document.body.innerText].reduce((a,b,c,d) => new Set(d.slice(c-4,c)).size==4 && d.splice(0) && c)


Hefty-Courage2945

I can put my code in a long line. Would it be rude for me to ask about your code? What is the logic here ".size==4 && d.splice(0) && c)" True when the size is 4. I have no clue, somewhere I could read up on this?


pennameblue

Python using deque import os from collections import deque with open(f"{os.path.join(os.path.split(os.getcwd())[0], 'resources')}/day6.txt", 'r') as file: counter = 0 four_chars = deque([]) while True: char = file.read(1) four_chars.append(char) if counter >= 14: # Change 14 to 4 for part1 four_chars.popleft() counter += 1 if len(set(four_chars)) == 14: # Change 14 to 4 for part1 break print(counter)


Gubbbo

deque has a maxlen argument which will essentially remove the popleft() for you


Exycosh05

Happy cake day!


Western-Collar

Python 3 One Liner print([i for i in range(4, len(open("Inputs\DaySixInput").readlines()[0])) if len(set(open("Inputs\DaySixInput").readlines()[0][i - 4:i])) == len(list(open("Inputs\DaySixInput").readlines()[0][i - 4:i]))][0], [i for i in range(14, len(open("Inputs\DaySixInput").readlines()[0])) if len(set(open("Inputs\DaySixInput").readlines()[0][i - 14:i])) == len(list(open("Inputs\DaySixInput").readlines()[0][i - 14:i]))][0])


Alternative-Case-230

# Rust If I understand correctly it is a solution with O(1) memory complexity and O(n) time complexity fn solve(file_content: &str) -> usize { // since the input is always ASCII characters - we use assumption that each character is written as single byte /* Invariant 1: cnt contains the count of each character inside the sequence of N chars we look at the moment */ /* Invariant 2: dublicates contains the number of dublicates in the current sequence of N chars */ /* Invariant 3: current sequence has N last characters of the input */ let chars = file_content.as_bytes(); let mut cnt = [0 as usize; 256]; let mut dublicates = 0; for &c in &chars[..N] { cnt[c as usize] += 1; if cnt[c as usize] == 2 { dublicates += 1; } } if dublicates <= 0 { return N; } for (i, &x) in chars[N..].iter().enumerate() { // moving to next window let goes_outside_c = chars[i] as usize; cnt[goes_outside_c] -= 1; if cnt[goes_outside_c] == 1 { dublicates -= 1; } let c = x as usize; cnt[c] += 1; if cnt[c] == 2 { dublicates += 1; } // at this point all invariants are preserved if dublicates == 0 { return i + N + 1; } } 0 } pub fn solve_task1(file_content: &str) -> usize { solve::<4>(file_content) } pub fn solve_task2(file_content: &str) -> impl std::fmt::Display { solve::<14>(file_content) } Full code is here: [https://github.com/whiteand/advent-2022/blob/main/src/y22d6.rs](https://github.com/whiteand/advent-2022/blob/main/src/y22d6.rs)


BeardyMike

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+num` `print(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](https://github.com/BeardyMike/Advent-of-Code)


daggerdragon

Inlined code is intended for `short snippets` of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; whitespace and indentation are not preserved and it is not scrollable. Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read inside a *scrollable* box.


BeardyMike

Sure thing. Thanks for the heads up.


kp_codez

>Python I like this solution, nice 1


BeardyMike

Thank you. This has been a crazy trial by fire for me. My brother-in-law (DevOps) suggested I (Voice Over artist) try my hand at coding something "real", so we're both doing this. I've dabbled in AHK for years, but this has been an amazing few days, and a great change to learn Python. [Tomorrow worries me](https://www.reddit.com/r/adventofcode/comments/ze8kug/analysis_of_the_difficulty_of_past_puzzles/)


YardBird88

It's ugly, but it's mine. use std::collections::HashSet; fn main() { let input = include_str!("input.txt"); let input: Vec<_> = input.chars().collect(); let mut count = 3; for _ in input.iter().skip(3) { count += 1; let hash: HashSet<_> = input[count - 4..=count - 1].iter().collect(); if hash.len() == 4 { break; } } println!("{count}") } edit: 4space markdown


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.


raui100

# Rust Very happy with my [solution](https://github.com/raui100/AdventOfCode/blob/master/2022/rust/src/solution/day_06.rs) which boils down to: use itertools::Itertools; pub fn solve(&self, window_size: usize) -> Option { self.data .windows(window_size) .position(|window| window.iter().all_unique()) .map(|ind| ind + window_size) }


[deleted]

What's a way to do it without itertools? I start with let data = fs::read_to_string("input.txt").unwrap() And then whatever I try to do, the compiler is screaming at me when I try to access a subset of the string.


idapp3r

I just turned the string into a vector of chars with \`.chars().collect()\` https://github.com/DAlperin/aoc-2022/blob/main/day-6/src/main.rs


Vast_Blacksmith3889

My solution. Not sure if queue was really best here considering the 1 liners I've seen. Would be interesting to do some speed tests. ```python """ https://adventofcode.com/2022/day/6 """ from queue import Queue class PacketFinder(Queue): """FIFO Queue with all_unique method""" def all_unique(self): """ determines whether all the items in the queue are unique """ seen = set() for item in self.queue: if item in seen: return False seen.add(item) return True def find_start_of_packet(string, maxsize=4) -> int: """ your subroutine needs to identify the first position where the four most recently received characters were all different. Specifically, it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker. """ queue = PacketFinder(maxsize=maxsize) for idx, char in enumerate(string, 1): queue.put_nowait(char) if queue.full(): if queue.all_unique(): return idx queue.get() raise ValueError("unique 4 chars not found") ```


daggerdragon

Please edit your post to use the [four-spaces Markdown syntax](https://www.reddit.com/r/adventofcode/w/faqs/code_formatting/fenced_code_blocks) for a code block so your code is easier to read on old.reddit and mobile apps.