I was so focused on an efficient solution that it took me a while to get to this
Python solution
def find_unique_sequence_start(data: str, size: int) -> int:
"""Find the first substring of given `size` with unique chars."""
current_size, last_seen = 0, {}
for idx, char in enumerate(data, 1):
prev_idx = last_seen.get(char, idx - current_size - 1)
current_size = min(current_size + 1, idx - prev_idx)
if current_size == size:
return idx
last_seen[char] = idx
return -1
In hindsight I should have realized that the puzzle was small enough that a simpler and less efficient approach would have sufficient and faster to write.
BTW: @IsaacG How do you get the details tag and the syntax highlighting?
I considered building a custom set that would keep a counter of the items seen
and would remove them if the counter is 0, but I figured it’s probably not worth it. Re-creating the set every time seems fast enough, part 2 takes just 3 ms, part 1 is < 1 ms, so I’m not too fussed about it.
interface State {
signal: string;
}
export function parse(input: string): State {
return { signal: nonEmptyLines(input)[0] };
}
export function part1(parsed: State): string {
return seekMarker(parsed.signal, 4).toString();
}
export function part2(parsed: State): string {
return seekMarker(parsed.signal, 14).toString();
}
export function seekMarker(signal: string, markerSize: number): number {
for (let i = markerSize; i < signal.length; i += 1) {
const lastX = signal.slice(i - markerSize, i);
if (lastX.length === new Set(lastX).size) {
return i;
}
}
return NaN;
}
Quick Put Something Down ... Anything! Julia Solution
module day06
function part01()
input = readchomp("/Users/anagy/Documents/AdventOfCode2022/AdventOfCode2022-Julia/input/06/input.in")
count = 4
lastSeen = collect(input[1:4])
for c in input[5:end]
lastSeen = lastSeen[2:end]
append!(lastSeen, c)
count += 1
if length(unique(lastSeen)) == 4
break
end
end
count
end
function part02()
input = readchomp("/Users/anagy/Documents/AdventOfCode2022/AdventOfCode2022-Julia/input/06/input.in")
count = 14
lastSeen = collect(input[1:14])
for c in input[15:end]
lastSeen = lastSeen[2:end]
append!(lastSeen, c)
count += 1
if length(unique(lastSeen)) == 14
break
end
end
count
end
end
println("P01: $(day06.part01())")
println("P02: $(day06.part02())")
Prettified Julia Solution
module day06
function part01()
input = readchomp("/Users/anagy/Documents/AdventOfCode2022/AdventOfCode2022-Julia/input/06/input.in")
findfirst(i -> allunique(input[i:i+4-1]), 1:length(input)) + 4 - 1
end
function part02()
input = readchomp("/Users/anagy/Documents/AdventOfCode2022/AdventOfCode2022-Julia/input/06/input.in")
findfirst(i -> allunique(input[i:i+14-1]), 1:length(input)) + 14 - 1
end
end
println("P01: $(day06.part01())")
println("P02: $(day06.part02())")