Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created September 21, 2010 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/589427 to your computer and use it in GitHub Desktop.
Save rklemme/589427 to your computer and use it in GitHub Desktop.
#!/bin/env ruby19
Num = Struct.new :pre, :val do
def succ
self.class.new pre, val.succ
end
def to_s; "#{pre}#{val}" end
def inspect; "#{self.class.name}(#{self})" end
include Comparable
def <=>(o) to_a <=> o.to_a end
end
def Num(s)
%r{\A(\D*)(\d+)\z} =~ s or raise "bad arg %p" % s
Num.new $1, $2.to_i
end
module Enumerable
def rangify(&bl)
bl ||= lambda {|x, y| x == y ? x : (x..y)}
res = []
a = b = nil
each do |x|
case
when a.nil?
a = b = x
when x == b.succ
b = x
else
res << bl[a, b]
a = b = x
end
end
res << bl[a, b] unless a.nil?
res
end
end
test_data = [
[ '1', '2', '3', '4', '6', '7', '9', 'S1', 'S2' ],
[ '1', '2', 'S3', 'S4', 'S5', 'O6' ],
]
test_data.each {|td| td.map! {|s| Num(s)} }
test_data.each do |td|
r1 = td.rangify
r2 = td.rangify {|x,y| x == y ? x.to_s : "#{x}-#{y}"}
p td, r1, r2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment