Created
September 21, 2010 08:58
-
-
Save rklemme/589427 to your computer and use it in GitHub Desktop.
Solution suggestion for http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/370127
This file contains 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
#!/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