Skip to content

Commit 7fe21e7

Browse files
author
Robb Kidd
committed
2022 day 6 part 2
1 parent 3c402c4 commit 7fe21e7

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

2022/ruby/day06.rb

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ def self.go
66
end
77

88
def initialize(input=nil)
9-
@input = input || real_input
9+
@input = (input || real_input).strip
1010
end
1111

1212
def part1
1313
start_of_packet_marker(@input)
1414
end
1515

1616
def part2
17+
start_of_message_marker(@input)
1718
end
1819

1920
# @example
@@ -32,12 +33,35 @@ def part2
3233
# day.start_of_packet_marker('zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw') => 11
3334
#
3435
def start_of_packet_marker(buffer)
35-
chars = buffer.tr("\n","").chars
36-
scan = 3
36+
scan_for_length(buffer, 4)
37+
end
38+
39+
# @example
40+
# day.start_of_message_marker('mjqjpqmgbljsphdztnvjfqwrcgsmlb') => 19
41+
#
42+
# @example
43+
# day.start_of_message_marker('bvwbjplbgvbhsrlpgdmjqwftvncz') => 23
44+
#
45+
# @example
46+
# day.start_of_message_marker('nppdvjthqldpwncqszvftbrmjlhg') => 23
47+
#
48+
# @example
49+
# day.start_of_message_marker('nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg') => 29
50+
#
51+
# @example
52+
# day.start_of_message_marker('zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw') => 26
53+
#
54+
def start_of_message_marker(buffer)
55+
scan_for_length(buffer, 14)
56+
end
57+
58+
def scan_for_length(buffer, packet_length)
59+
chars = buffer.chars
60+
scan = lookback = packet_length - 1
3761
found = false
3862
while !found || scan < chars.length do
39-
check = chars[scan-3..scan]
40-
if check.uniq.length == 4
63+
check = chars[scan-lookback..scan]
64+
if check.uniq.length == packet_length
4165
found = true
4266
break
4367
end

0 commit comments

Comments
 (0)