連続した日付をカウントする
require 'active_support'
require 'active_support/core_ext'
current = Date.current.tomorrow
posted_days = [
current.advance(days: 1),
current.advance(days: 2),
current.advance(days: 3),
# - this day, not posted -
current.advance(days: 5),
current.advance(days: 6),
current.advance(days: 7),
current.advance(days: 8),
# - this day, not posted -
# - this day, not posted -
current.advance(days:10),
current.advance(days:11),
current.advance(days:12),
current.advance(days:13),
current.advance(days:14),
current.advance(days:15),
# - this day, not posted -
current.advance(days:17)
]
class StreakDays
def initialize(posted_days)
@posted_days = posted_days
@count_stock = [0]
calc_continuation_days
end
def longest_streak
@count_stock.max
end
private
def calc_continuation_days
count_stock = [0]
current = @posted_days.first
@posted_days.each do |posted_day|
if days_streak?(current, posted_day)
count_stock[-1] += 1
else
count_stock << 1
end
current = posted_day
end
@count_stock = count_stock
end
def days_streak?(a, b)
date_distance(a, b) == 1
end
def date_distance(current, next_day)
(current - next_day).to_i.abs
end
end
s = StreakDays.new(posted_days)
p s.longest_streak # => 6