Created
October 21, 2009 03:11
-
-
Save udzura/214815 to your computer and use it in GitHub Desktop.
triggered by [http://builder.japan.zdnet.com/sp/ruby-doukaku-panel/story/0,3800086254,20369264,00.htm]
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
require 'enumerator' | |
def hyphenize_numbers *args | |
src = args.map{|v| v.to_i} | |
src.sort!.uniq! | |
dst = [[ src[0] ]] | |
src.each_cons(2) do |cons| | |
if cons[1] - cons[0] > 1 | |
dst << [] | |
end | |
dst.last << cons[1] | |
end | |
p src | |
puts "--------" | |
p dst | |
dst.map! do |nums| | |
if nums.length == 1 | |
nums[0].to_s | |
else | |
"#{nums.first}-#{nums.last}" | |
end | |
end | |
puts "--------" | |
puts dst.join(", ") + "." | |
end | |
if __FILE__ == $0 | |
SRC = [1, 2, 3, 5, 6, 7, 8, 9, 12, 14] | |
hyphenize_numbers *SRC | |
=begin | |
#=> | |
[1, 2, 3, 5, 6, 7, 8, 9, 12, 14] | |
-------- | |
[[1, 2, 3], [5, 6, 7, 8, 9], [12], [14]] | |
-------- | |
1-3, 5-9, 12, 14. | |
=end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment