Unable to load image

Advent of Code day 6

was preparing my butthole after the last one but ended up being the fastest one i've done :marseyexcited:

with open("day6input.txt") as f:
    input = f.read()

# part 1

for i in range(len(input)):
    marker = set(input[i:i+4])
    if len(marker) == 4:
        answer = i + 4
        break

print(answer)

# part 2 

for i in range(len(input)):
    marker = set(input[i:i+14])
    if len(marker) == 14:
        answer = i + 14
        break

print(answer)
28
Jump in the discussion.

No email address required.

r←⊃1⌷⊢⎕FIO[49] 'day6raw.txt'
{1-⍨⍵+⍵⍳⍨↑¨⍴¨⍵∪/r}¨4 14
Jump in the discussion.

No email address required.

is my browser even rendering those characters properly?

Jump in the discussion.

No email address required.

:#marseywtf:

Jump in the discussion.

No email address required.

King reduce that input file name, you're wasting bytes. :marseykingcrown:

Jump in the discussion.

No email address required.

Thanks for the advice king, two lines was bloat

{1-⍨⍵+⍵⍳⍨↑¨⍴¨⍵∪/⎕FIO[26]'6'}¨4 14

Jump in the discussion.

No email address required.

Deduplicated and modestly cleaned up version again. Used a set comprehension when actually solving it because I didn't know how the set() constructor builtin handled iterables. Strangely easy for a Day 6; guess we're gonna get reamed tomorrow.

![](/images/1670306834703174.webp)

Jump in the discussion.

No email address required.

We can only hope.

Jump in the discussion.

No email address required.

Yeah it was too easy. I'm wondering if doing it really inefficiently is going to come back to haunt some people later (although you'd have to have a really massive dataset for that to even be an issue at all).

Jump in the discussion.

No email address required.

how would it haunt people?

trans lives matter

Jump in the discussion.

No email address required.

I don't know, what if the guy gave you 3 megabytes of data and asked you to identify the first sequence where 900,000 characters in a row were in a certain pattern?

Jump in the discussion.

No email address required.

but the puzzle input is only however many bytes long? we aren't going too be reusing it?

trans lives matter

Jump in the discussion.

No email address required.

I know, it's more like I'm trying to imagine some future puzzle in which it was important that we understand something about data processing from this that most of us did not because the puzzle was too easy to solve without concern for efficiency. I'm probably giving the guy too much credit though, maybe he just got lazy on this one.

Jump in the discussion.

No email address required.

ur r-slurred

Jump in the discussion.

No email address required.

Yeah, that's true.

Jump in the discussion.

No email address required.

k = 14
file = open("input.txt")
c=file.read(k-1)
i = k-1
while True:
    c+= file.read(1)
    i+=1
    if(len(set(c[-k:]))) == k: break;
print(i)

No part1/2 because all i had to do is change one variable. They must be being generous before the big ones

Jump in the discussion.

No email address required.

ez

MESSAGE_LENGTH = 14

index = 0
while len(set([*message[index:index+MESSAGE_LENGTH]])) != MESSAGE_LENGTH: index+=1
print(index+MESSAGE_LENGTH)

trans lives matter ![](/i/chud/supportjews.webp)

Jump in the discussion.

No email address required.

Change 14 to 4 for part one

from collections import deque


with open('./input6.txt') as infile:
    text =infile.read().strip()


q = deque(maxlen=14)


for i, char in enumerate(text,1):
    q.append(char)
    if i < 14: continue
    if len(set(q)) == 14:
        print(i)
        break
Jump in the discussion.

No email address required.

nothing special

![](/images/16703049042926471.webp)

Jump in the discussion.

No email address required.

poop = {}

:#marseybruh:

trans lives matter

Jump in the discussion.

No email address required.

Naming is hard :platydown:

Jump in the discussion.

No email address required.

finally awake for it and r-slurred because i forgot that strings are iterables

![](/images/1670304773890732.webp)

Jump in the discussion.

No email address required.

My brute force solution

#include <iostream>

#define PREAMBLE_WINDOW_SIZE 4
#define MESSAGE_WINDOW_SIZE 14

inline bool contains_duplicates(const std::string& window)
{
  // O(n²) meh
  for(size_t i = 0; i < window.length(); i++)
    for(size_t j = 0; j < window.length(); j++)
      if(i != j and window[i] == window[j])
        return 1;
  return 0;
}

int main()
{
  std::string line;
  std::getline(std::cin, line);
  size_t i = 0;

  for(; i < line.length() - PREAMBLE_WINDOW_SIZE; i++)
  {
    if(not contains_duplicates(line.substr(i, PREAMBLE_WINDOW_SIZE)))
    {
      // PART A
      //std::cout << (i + PREAMBLE_WINDOW_SIZE) << std::endl;
      // return 0;
      break;
    }
  }

  for(; i < line.length() - MESSAGE_WINDOW_SIZE; i++)
    if(not contains_duplicates(line.substr(i, MESSAGE_WINDOW_SIZE)))
    {
      // PART B
      std::cout << (i + MESSAGE_WINDOW_SIZE) << std::endl;
      return 0;
    }

  return -1;
}

Discuss

Jump in the discussion.

No email address required.

based and sexy Indian dude pilled

trans lives matter

Jump in the discussion.

No email address required.

iostream :!marseyyikes:

Jump in the discussion.

No email address required.

I'm getting 2019 Intcode flashbacks, where AoC had us build up a signal processor over about 10 days. This was too easy, we haven't seen the last of it.

Jump in the discussion.

No email address required.

:#marseyworried:

i wonder how long it's going to be before there's a task i completely give up on

Jump in the discussion.

No email address required.

He normally throws a nasty question in around day 16, at that point I either ragequit AoC for the year or just skip that one day.

Jump in the discussion.

No email address required.

I'm too embarrassed to post my entire answer, but I parsed each part of the puzzle input one character at a time, appending it to a string of characters, and validating each character in the string was unique or not.

I assumed that the first N characters (N being equal to the message token length, so 4 for part A and 14 for part B), were not going to have uniques (imagine if the very first four numbers were all unique and the answer was just 4 lmao) so I read in N number of characters all at once, then from there, validated that string to see if there were any dupes, and then would push a new character to the end and pop off the front, and then validate the new string, repeat until you get N unique characters.

My validation algorithm is bare-bones stupid, literally just a for-loop nested inside another for-loop, checking each character one-by-one. This would be monstrously inefficient if the input or message-length was huge but hey, the point is to do it fast right?

Jump in the discussion.

No email address required.

I would recommend learning some low level computer architecture/digital systems.

Boolean logic, shift registers, any of which would remind you very quickly how much of a monstrously bad Idea what you did was and will make you a better coder.

But you did it, you perservered, so its not completely hopeless

Jump in the discussion.

No email address required.

Can you go into more detail about

>Boolean logic, shift registers

?

I've processed packets of data over a stream before, but usually you have the luxury of either knowing the packet size ahead of time (which this puzzle omits), and/or having a checksum to verify its integrity. And you're usually not blindly checking each byte against the other, and you can just memcpy it into a struct to fill out all your members.

Jump in the discussion.

No email address required.

I'm assuming you enjoy the low level aspects since youre working in c++

c++ has the unordered_set template which is the equivalent of what you've been seeing in other solutions so you could accomplish the same much faster.

usually you have the luxury of either knowing the packet size ahead of time

For the puposes of this problem, this is actually not important. You're only doing it for one file, and you are guaranteed that it will happen at some point. You could select all in notepad++ and check char count or just iterate infinitely through the stream and not give a frick.

And you're usually not blindly checking each byte against the other

From an optimization standpoint, you're redoing 90+% of your comparisons every time you shift in a new byte. You already know if the first n-1 values are unique, so you can either disregard entirely until that's resolved or only have to iterate through the array once to check the newest one

Granted none of this is ideal for just banging out a solution as fast as you can. Its just ideas for what would be better in a proper environment

Jump in the discussion.

No email address required.

or u could do it in three lines of python :marseyzoomer:

index = 0
while len(set([*message[index:index+MESSAGE_LENGTH]])) != MESSAGE_LENGTH: index+=1
print(index+MESSAGE_LENGTH)

trans lives matter ![](/i/chud/supportjews.webp)

Jump in the discussion.

No email address required.

what does the asterisk do

Jump in the discussion.

No email address required.

yeah I'm there with you, and unless you have access to those things (not all languages have the luxury of direct memory access) I don't see what the better siolutino would be. Possibly just read it all iinto memory and check a substring?

Jump in the discussion.

No email address required.

PLEASE HELP :(

#include <stdio.h>

int auth(char *buffer, int index, const int seq){
	int result = 1;
	for(int i=1;i<=seq;i++){
		result = result && (buffer[index] != buffer[index - i]);
	}
	return result;
}

int main(void){
	FILE *f = fopen("input.txt","r");
	char buffer[8192];
	fgets(buffer,8192,f);
	
	int i;
	const int num = 14;
	for(i=num;i<8192;i++){
		int result = 1;
		
		for(int k=0;k<num;k++){
			result = result && auth(buffer,i-k,num-k);
			if(result == 0)
				break;
		}
		if(result == 1)
			break;
		
	}
	fclose(f);
	printf("%d\n",i);
	return 0;
}

Idk what's wrong with my code. It gave the correct answer for 4 consecutive characters but for 14 it just goes through the entire string without finding a match. I ended up running the solutions for 13 consecutive characters, 12 consecutive chars, etc and noticed that the answers were always incremented:

3: 1099

4:1100

5:1101

6:1107

7:1108

8:1154

9:1155

10:1321

11:1322

12:2419

13:2420

So I just guessed 2421 for 14 and it was right... It's weird because I tried the test inputs and got the correct answer for them all except for mjqjpqmgbljsphdztnvjfqwrcgsmlb. Apparently the answer is supposed to be 19 but that makes no sense to me because the 19th character is j and there is also a j for the 10th character. Maybe I am fundamentally misunderstanding the problem. Either way I give up :#marseygiveup:

Jump in the discussion.

No email address required.

You sat down and wrote all this shit. You could have done so many other things with your life. What happened to your life that made you decide writing novels of bullshit here was the best option?

Jump in the discussion.

No email address required.

:#marseysad:

Jump in the discussion.

No email address required.

It's not that nothing in the buffer equals the first character in the buffer. It's that there are not two equal characters in the rolling buffer.

Jump in the discussion.

No email address required.

Yes

Jump in the discussion.

No email address required.

You count forwards from the 19th character, not backwards.

Jump in the discussion.

No email address required.

There are only 30 characters though

Jump in the discussion.

No email address required.

It's weird that he doesn't explain that.

Jump in the discussion.

No email address required.

input="string here"
seen=[]
for i in range(len(input)):
    ch=input[i]
    seen.append(ch)
    if (seen.index(ch)!=len(seen)-1):
        seen=seen[seen.index(ch)+1:]
    if(len(seen)==14): #4 for part 1
        print(i+1)
Jump in the discussion.

No email address required.

i = "" + fs.readFileSync("input")

q = l => a => [...Array(a.length)].map((_,i) => [...new Set(a.slice(i-l+1,i+1))].length == l).indexOf(true) + 1

part 1: q(4)(input)

part 2: q(14)(input)

today was weirdly easy. also, JS needs a better stdlib, the above is vanilla JS but incredibly ugly. the JS committee adds a few functions every year, not enough

Jump in the discussion.

No email address required.

I wish I stayed up for this one, took me about 5 minutes lol.

foo = ""
with open('day6_input.txt', 'r') as inp:
    foo = inp.read()
a = 4 # a = 14 for part 2
index = a
while len([*foo[index-a:index]]) > len(set([*foo[index-a:index]])):
    index += 1
print(index)
Jump in the discussion.

No email address required.

great filter when

A = char(readlines("input.txt","EmptyLineRule","skip"));
N = [4,14];

I = zeros(1,length(N));
Cond = false(1,length(N));
i = 1;
while all(Cond) && (i+1<=length(A))
    for j = 1:length(N)
        if (Cond(j)) && (length(unique(A(i:i+N(j)-1))) == N(j))
            I(j) = i+N(j)-1;
            Cond(j) = true;
        end
    end
    i = i+1;
end

fprintf("Part 1 : %d\n",I(1))
fprintf("Part 2 : %d\n",I(2))
Jump in the discussion.

No email address required.

@Jinglevann it's me, ya boy

Is markdown shit being active in code blocks a normal thing? Can't use ~ in these then

Jump in the discussion.

No email address required.

fixed king, my apologies

Jump in the discussion.

No email address required.

:#chadthankskingcapy:

Jump in the discussion.

No email address required.

I'm not super familiar with what programming language you're using but "set" is a data structure with unique keys, right? and if you stick four characters in a set and any are dupes, the size of the container will be less than 4 (or 14)? Honestly I had that idea too at first but didn't know off the top of my head how to do that in C++ and I figured a dumbass manually-check-each-character algorithm would take my brain less time to understand. I like your answer a lot.

Jump in the discussion.

No email address required.

yeah, sets in python are basically just an unordered collection with no duplicates that have methods like intersection(), union() and issuperset() that are supposed to be analagous to operations on sets in mathematics. they have been pretty useful so far for AoC - used them for days 3 and 4 also.

Jump in the discussion.

No email address required.

Very easy today. Not going to optimize. I'm not going to do it.

with open('testinput', 'r') as f:

    for line in f:

        markerFound = False

        count = 0

        line = line.strip()

        curFound = ''

        for ch in line:

            curFound += ch

            if count >= 13 and not markerFound:

                good = True

                for c in curFound:

                    if curFound.count(c) > 1:

                        good=False

                if not good:

                    curFound = curFound[1:]

                if good: 

                    markerFound = True

                    break

            count += 1

        print('Line Count:', count + 1)
Jump in the discussion.

No email address required.

guaranteed O(n) solution, if only javascript was a real language and had proper hashmaps with size tracking

const l = 14; // change for code length
const h: any = [];
let d = 0;
console.log(fs.readFileSync(process.argv[2], 'utf-8')
  .split('').map(ch => ch.charCodeAt(0)).reduce((p, c, i, s,) => p
     ((h[c] ??= 0)  1) && ++h[c] && (h[c] === 2 ? ++d : 1) && (i >= l-1) && !d && i+1
    || (i >= l-1) && (h[s[i-(l-1)]]--) && (h[s[i-(l-1)]] === 1 ? d-- : 1) && 0
    || 0
  , 0));
Jump in the discussion.

No email address required.

c++

spent some time to find a O(1) for adding and checking if string is unique and then just gave up and ended up on O(n), with n being the length of the substring


bool isUnique(const std::string& substring) {
	std::array<bool, 26> chars{false};

	for (std::size_t i{0 }; i < substring.size(); ++i) {
		if (chars[substring[i] - 'a']) return false;
		chars[substring[i] - 'a'] = true;
	}
	return true;
}


int solution(const std::string& buf, int word_size) {
	std::string substring;
	std::size_t idx{ 0 };

	for (std::size_t i{ 0 }; i < buf.size(); ++i) {
		if (substring.size() < word_size) substring += buf[i];
		if (substring.size() == word_size && isUnique(substring)) {
			idx = i;
			break;
		}
		else {
			substring.erase(0, 1);
		}
		substring += buf[i];
	}
	return idx;
}

int main() {
	std::ifstream file("input.txt");

	std::string buf;
	std::getline(file, buf);
	auto a = std::chrono::high_resolution_clock::now();
	int p1 = solution(buf, 4);
	auto b = std::chrono::high_resolution_clock::now();
	int p2 = solution(buf, 14);
	auto c = std::chrono::high_resolution_clock::now();


	auto ab = std::chrono::duration_cast<std::chrono::microseconds>(b - a);

	auto bc = std::chrono::duration_cast<std::chrono::microseconds>(c - b);

	std::cout << "Part One: " << p1 << " Time: " << ab << '\n'
		<< "Part Two: " << p2 << " Time: " << bc << '\n';
}

Jump in the discussion.

No email address required.

Okay here is the O(1) version for checking if string is unique



int solution(const std::string& buf, int word_size) {
	std::string substring;
	std::size_t idx{ 0 };

	std::array<int, 26> uniqueChars{ 0 }; 

	int distinct_count{ 0 }; 

	for (std::size_t i{ 0 }; i < word_size; ++i) { 
		if (uniqueChars[buf[i] - 'a'] == 0) ++distinct_count;
		++uniqueChars[buf[i] - 'a']; 
	}

	for (std::size_t i = word_size ; i < buf.size(); ++i) {
		if (uniqueChars[buf[i - word_size] - 'a'] == 1) { 
			--distinct_count;							 
		}

		--uniqueChars[buf[i - word_size] - 'a'];

		if (uniqueChars[buf[i] - 'a'] == 0) ++distinct_count;

		++uniqueChars[buf[i] - 'a'];

		if (distinct_count == word_size) {
			idx = i + 1;
			break;
		}
	}
	return idx;
}

int main() {
	std::ifstream file("input.txt");

	std::string buf;
	std::getline(file, buf);
	auto a = std::chrono::high_resolution_clock::now();
	int p1 = solution(buf, 4);
	auto b = std::chrono::high_resolution_clock::now();
	int p2 = solution(buf, 14);
	auto c = std::chrono::high_resolution_clock::now();


	auto ab = std::chrono::duration_cast<std::chrono::microseconds>(b - a);

	auto bc = std::chrono::duration_cast<std::chrono::microseconds>(c - b);

	std::cout << "Part One: " << p1 << " Time: " << ab << '\n'
		<< "Part Two: " << p2 << " Time: " << bc << '\n';
}

The first version ran in(without reading from the file):
Part One: 1109 Time: 24us
Part Two: 3965 Time: 62us

The second version in:
Part One: 1109 Time: 3us
Part Two: 3965 Time: 8us

Jump in the discussion.

No email address required.

No, don't reply like this, please do another wall of unhinged rant please.

Jump in the discussion.

No email address required.

Sorry ma'am, looks like his delusions have gotten worse. We'll have to admit him.

Jump in the discussion.

No email address required.

this was sort of easy

using static System.Linq.Enumerable;

namespace AOC2022.Puzzles;

public class Day6 : IPuzzle
{
	private readonly int _totalLength;
	private readonly string _actualInput;

	public Day6(IReadOnlyList<string> linesFromFile)
	{
		_actualInput = linesFromFile[0];
		_totalLength = _actualInput.Length;
	}

	public void SolveFirstPuzzle()
	{
		const int sopLength = 4;
		var result = Range(sopLength, _totalLength)
			.First(x => 
				_actualInput.Substring(x - sopLength, sopLength).ToHashSet().Count == sopLength);
		Console.WriteLine(result);
	}

	public void SolveSecondPuzzle()
	{
		const int somLength = 14;
		var result = Range(somLength, _totalLength)
			.First(x => 
				_actualInput.Substring(x - somLength, somLength).ToHashSet().Count == somLength);
		Console.WriteLine(result);
	}
}

can improve more but I got work today :( thx to rider for making it almost one line lmao

![](/images/16703170672943056.webp)

Jump in the discussion.

No email address required.

ez


package six

import (
	"bufio"
	"bytes"
	"os"
)

const packet_size int = 4
const message_size int = 14

func One() int {
	var deliver int
	var buffer []byte

	fp, _ := os.Open("six.txt")
	defer fp.Close()
	rd := bufio.NewReader(fp)

	for i := 0; ; i++ {
		ch, _ := rd.ReadByte()
		buffer = append(buffer, ch)

		if len(buffer) > packet_size {
			for _, x := range buffer[i-packet_size : i] {
				sep := string(x)
				deliver += bytes.Count(buffer[i-packet_size:i], []byte(sep))
			}

			if deliver == packet_size {
				return i
			} else {
				deliver = 0
			}
		}
	}
}

func Two() int {
	var deliver int
	var buffer []byte

	fp, _ := os.Open("six.txt")
	defer fp.Close()
	rd := bufio.NewReader(fp)

	for i := 0; ; i++ {
		ch, _ := rd.ReadByte()
		buffer = append(buffer, ch)

		if len(buffer) > message_size {
			for _, x := range buffer[i-message_size : i] {
				sep := string(x)
				deliver += bytes.Count(buffer[i-message_size:i], []byte(sep))
			}

			if deliver == message_size {
				return i
			} else {
				deliver = 0
			}
		}
	}
}
Jump in the discussion.

No email address required.

:#marseyn:

Jump in the discussion.

No email address required.

:#marseyww1german1:

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.