Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce consecutive integers in an array to hyphenated range expressions?

In JavaScript, how can I convert a sequence of numbers in an array to a range of numbers? In other words, I want to express consecutive occurring integers (no gaps) as hyphenated ranges.

[2,3,4,5,10,18,19,20] would become [2-5,10,18-20]

[1,6,7,9,10,12] would become [1,6-7,9-10,12]

[3,5,99] would remain [3,5,99]

[5,6,7,8,9,10,11] would become [5-11]

like image 587
gokul Avatar asked Feb 16 '10 05:02

gokul


People also ask

How do you find consecutive integers in an array?

1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

What is the range of consecutive numbers?

Range of a set of numbers is the difference of highest number & the lowest number . Consecutive integers are a set which when arranged in ascending or descending order , the common difference of any two consecutive number is 1.


1 Answers

Here is an algorithm that I made some time ago, originally written for C#, now I ported it to JavaScript:

function getRanges(array) {   var ranges = [], rstart, rend;   for (var i = 0; i < array.length; i++) {     rstart = array[i];     rend = rstart;     while (array[i + 1] - array[i] == 1) {       rend = array[i + 1]; // increment the index if the numbers sequential       i++;     }     ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);   }   return ranges; }  getRanges([2,3,4,5,10,18,19,20]); // returns ["2-5", "10", "18-20"] getRanges([1,2,3,5,7,9,10,11,12,14 ]); // returns ["1-3", "5", "7", "9-12", "14"] getRanges([1,2,3,4,5,6,7,8,9,10]) // returns ["1-10"] 
like image 164
Christian C. Salvadó Avatar answered Sep 22 '22 06:09

Christian C. Salvadó