#Day 06 - Solutions
87 messages · Page 1 of 1 (latest)
package main
import (
_ "embed"
"fmt"
)
//go:embed input
var input string
func main() {
// Part 1
fmt.Println(markerIndex(4))
// Part 2
fmt.Println(markerIndex(14))
}
func markerIndex(markerLen int) int {
for i := 0; i < len(input); i++ {
if isMarker(input[i : i+markerLen]) {
return i + markerLen
}
}
return -1
}
func isMarker(s string) bool {
for i := 0; i < len(s); i++ {
for j := i + 1; j < len(s); j++ {
if s[i] == s[j] {
return false
}
}
}
return true
}
map ez
boring af
haha
eventually I think. its still first week
There wasn't a lot to work with today... ||```rb
Day 6: We had to fix a handheld communicator
$stdin = open 'day6.txt'
"#
or
:"
S=
-> *
x,n{(n..).
find{L[_1-
n,n].chars
.uniq.size
.==n;}};L=
gets;p([S[
4],S[14]])
works out well for you as the drawing is not that complicated to make lol
i could not figure out what to make
like... checksums?
then someone suggested a handheld radio
i spent forever trying to figure out how to get the second knob to be a *
lool
package main
import (
"fmt"
"os"
"strings"
)
func main() {
f, _ := os.ReadFile("./input.txt")
fmt.Println(getFirstMarker(string(f), 4))
fmt.Println(getFirstMarker(string(f), 14))
}
func getFirstMarker(s string, size int) int {
for i := size; i < len(s); i++ {
if isUnique(s[i-size:i]) {
return i
}
}
return 0
}
func isUnique(s string) bool {
ss := strings.Split(s, "")
set := make(map[string]struct{})
for _, v := range ss {
set[v] = struct{}{}
}
return len(set) == len(ss)
}
why is it so easy today 🤣
very easy day lol
I thought we already had a catch-up day D:
https://github.com/SHA65536/AdventOfCodeGo/blob/main/2022/day06/day06.go
what is embed? like what it do
embed is super useful. In this case, the use of //go:embed input casts the content of the file input to the variable input as a string
so you don't gotta do f, err := os.ReadFile("input") intput := string(f)
it basically does that for you with a comment
i need some kind of sheet where every useful feature is listed :/
https://github.com/Nigma1337/AOC2022/blob/master/day_6/main.go
hashmaps go brrr.
I learnt that len of a hashmap is o(1), because the hashmap struct has a count value, that's cool!
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, _ := os.Open("input.txt")
defer f.Close()
buf := bufio.NewScanner(f)
var result int
for buf.Scan() {
line := buf.Text()
var i int
for i = 0; i < len(line)-3; i++ {
fourChars := line[i : i+4]
uniq := make(map[rune]bool)
for _, letter := range fourChars {
uniq[letter] = true
}
if len(uniq) == 4 {
result = i + 4
fmt.Println("Part 1:", result)
break
}
}
}
}```
https://github.com/mohanavel15/advent-of-code/blob/main/2022/day06.go
func Solution(input string) {
input_len := len(input)
for i := range input {
if input_len-i < 3 {
break
}
last_index := i + 4 // i + 4 for question 1 and i + 14 for question 2
marker := input[i:last_index]
has_repeat := false
for mi, r := range marker {
if strings.IndexRune(marker[mi+1:], r) != -1 {
has_repeat = true
break
}
}
if !has_repeat {
fmt.Println("Answer:", last_index)
break
}
}
}
why do you loop through chars in updateAggregate instead of something like chars[1:]?
Oh i see
no i dont
Because I’ve not yet been graced with a brilliant teacher like yourself. 😁, that’s a great idea and certainly would’ve made it more efficient and more readable.
Thanks for taking the time to look it over and share your thoughts. ☺️
No problem, i'm actually rather new to go, so i was also looking to learn something 😅
Today was very easy
d6p1 :: String -> Int -> Int
d6p1 a b = if (length . fromList . take 4) a == 4 then b + 4 else d6p1 (tail a) (b + 1)
d6p2 :: String -> Int -> Int
d6p2 a b = if (length . fromList . take 14) a == 14 then b + 14 else d6p2 (tail a) (b + 1)
what lang is this even
Haskell.
You can write the entire solution for today as:
main :: IO ()
main = do
input <- readFile "06.txt"
print $ solve input 0 4
print $ solve input 0 14
where
solve a b c = if (length . fromList . take c) a == c then b + c else solve (tail a) (b + 1) c
import sys
data = sys.stdin.read().strip()
packet, message = -1, -1
for i in range(len(data)):
if len({*data[i:i+4]}) == 4 and packet == -1:
packet = i + 4
if len({*data[i:i+14]}) == 14 and message == -1:
message = i + 14
if packet != -1 and message != -1:
break
print(packet, message)
```not bad
21st place on our leaderboard lol
hopefully i can score good tonight
Lets obscure it.
data = sys.stdin.read().strip()
print(next(filter(lambda i: len({*data[i:i+4]}) == 4, range(len(data)))) + 4, next(filter(lambda i: len({*data[i:i+14]}) == 14, range(len(data)))) + 14)
As we say around here 😄
lol epic
throw a lambda and a __import__ in there to avoid the declaration of data and ur good lol
or just input().strip() i guess
it's only one line input
You wanna get really dirty 😏
lmao
(lambda data: print(next(filter(lambda i: len({*data[i:i+4]}) == 4, range(len(data)))) + 4, next(filter(lambda i: len({*data[i:i+14]}) == 14, range(len(data)))) + 14))(input())
``` here
nice
so much easier than yesterday
:- use_module(library(dcg/basics)).
:- use_module(library(clpfd)).
numbers([R]) --> nonblank(R).
numbers([R|Rs]) --> nonblank(R), numbers(Rs).
marker(Index, Length, [H|Tail], Result):-
length(Sub, Length),
append(Sub, _, [H|Tail]),
all_distinct(Sub),
Result is Index + Length.
marker(Index, Length, [_|Tail], Result):-
NIndex is Index + 1,
marker(NIndex, Length, Tail, Result).
:-
phrase_from_file(numbers(A), 'input.txt'),
marker(0, 4, A, P1),
marker(0, 14, A, P2),
format("~p\n", P1),
format("~p\n", P2),
halt.
Some more prolog
Today was fun, simple but fun
https://github.com/Pedro-Pessoa/goadventofcode/blob/main/solutions/2022/day_6/day_6.go
Out of curiosity. How come you use embedfs instead of just calling os.Open?
When using embed it might ne easier to define the type as []byte
That way you don’t have to open and readall
You can os.ReadFile too
Embeding the file directly as string or bytes is simple and a struggle free feature because it just works.
They aren’t doing that though 😉
Simplified to this: ```go
func solve(data []byte, n int) {
outer:
for i := 0; i < len(data); i++ {
var bits uint64
for j := 0; j < n; j++ {
if bits&(1<<(data[i+j]-'a')) != 0 {
continue outer
}
bits |= 1 << (data[i+j] - 'a')
}
// if we got here, all chars were different
fmt.Println(i + n)
return
}
}```
Simplified??

By simplified I meant I reduced LOC
But yeah this would be much simpler with a map hehe
thinking the same lol
no idea what pedro did
Wait, wtf
~~Benchmarking that yields ~~
BenchmarkSolve-16 34561 33238 ns/op 0 B/op 0 allocs/op
~~Change it to ~~```go
func solve(data []byte, n int) {
outer:
for i := 0; i < len(data); i++ {
var bits uint64
for j := 0; j < n; j++ {
v := data[i+j] - 'a'
if bits&(1<<v) != 0 {
continue outer
}
bits |= 1 << (v)
}
// if we got here, all chars were different
_ = i + n
return
}
}```And now the benchmark is
BenchmarkSolve-16 56258526 21.87 ns/op 0 B/op 0 allocs/op
???
It is not the println btw
I removed that for both benchs
They use a bit mask to keep track of what numbers have been seen instead of a map
When the bit wise and yields something other than 0 there is a duplicate so they skip that entry
How do you benchmark that? Ive tried doing pprof with cpuprofile on my code but no results
Have the func return data. Compiler might be doing something too smart
Fair will do
func BenchmarkSolve(b *testing.B) {
input, err := Input.Open("day_6_input.txt")
if err != nil {
log.Fatalf("failed to open input file: %s\n", err)
}
defer input.Close()
data, err := io.ReadAll(input)
if err != nil {
log.Fatalf("failed to read all: %#v\n", err)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
solve(data, 14)
}
}```
Saving this for tomorrow, Thanks a ton!
I was being dumb and doing v-'a' instead of just v

var marker_appears int
var marker string
for i := 0; i < len(input); i++ {
if len(marker) < 4 {
if !strings.Contains(marker, string(input[i])) {
marker = fmt.Sprintf("%v%v", marker, string(input[i]))
} else {
marker = ""
}
} else {
marker_appears = i + 1 //because it's after
break
}
}
fmt.Printf("the input is %v in length\n", len(input))
fmt.Printf("the marker is %v\n", marker)
fmt.Printf("marker appears at %v\n", marker_appears)
not sure what im doing wrong here..
oop, nvm i see now
looks good, except it should be i and not i+1, and you shouldn't completly delete the marker