-
-
Save shajith/e7fae82ce1e9d7527f9b34d0fa2f7ca7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ranges(io, max_step = 1) | |
in_range = false | |
first = nil | |
last = nil | |
io.each_line do |line| | |
id = line.to_i | |
if first.nil? | |
first = id | |
last = id | |
next | |
end | |
if in_range | |
if id - last > max_step | |
yield first, last if last - first > 1 | |
in_range = false | |
end | |
elsif id - last <= max_step | |
in_range = true | |
first = last | |
end | |
last = id | |
end | |
if in_range | |
yield first, last | |
end | |
end | |
io = StringIO.new(<<-EOS | |
1 | |
2 | |
3 | |
5 | |
6 | |
8 | |
11 | |
12 | |
13 | |
15 | |
16 | |
EOS | |
) | |
p ranges(io) {|x, y| puts [x,y].inspect } | |
p ranges(io, 2) {|x, y| puts [x,y].inspect } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment