Skip to content

Instantly share code, notes, and snippets.

@gareth
Last active July 24, 2017 13:42
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 gareth/73835bad2a68b13b237bb8459e0593bc to your computer and use it in GitHub Desktop.
Save gareth/73835bad2a68b13b237bb8459e0593bc to your computer and use it in GitHub Desktop.

Range compression

Write a function compress_ranges that receives an array of integers, and returns a string where consecutive integers are replaced with a range showing the first and last number in that run.

You can assume the array only contains distinct integers, and is always sorted in ascending order.

Test cases

compress_ranges([4,5,6,7])
compress_ranges([1,3,4,5])
compress_ranges([-2,-1,0,1,3,5])
compress_ranges([-5,-4,-3,-1,1])
compress_ranges([-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20])

Expected output

> compress_ranges([4,5,6,7])
=> "4-7"

> compress_ranges([1,3,4,5])
=> "1,3-5"

> compress_ranges([-2,-1,0,1,3,5])
=> "-2-1,3,5"

> compress_ranges([-5,-4,-3,-1,1])
=> "-5--3,-1,1"

> compress_ranges([-6,-3,-2,-1,0,1,3,4,5,7,8,9,10,11,14,15,17,18,19,20])
=> "-6,-3-1,3-5,7-11,14-15,17-20"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment