[ create a new paste ] login | about

Link: http://codepad.org/7lIh6ZsC    [ raw code | output | fork ]

Ruby, pasted on Sep 20:
1
2
3
4
5
6
7
8
9
10
11
12
13
def compaction(array)
  return array if array.size == 0
  result = [[array.shift]]
  array.each{|n|
    result.last.last == n - 1 ? result.last << n : result << [n] 
  }
  result.map!{|ary|
    ary.size >= 3 ? "#{ary.first}-#{ary.last}" : ary.map{|n| n.to_s }.join(", ")
  }
  result.join(", ")
end

p compaction([1, 2, 3, 10, 11, 20, 100, 101, 102, 200])


Output:
1
"1-3, 10, 11, 20, 100-102, 200"


Create a new paste based on this one


Comments: