How to convert sequence of numbers in an array to

2020-01-30 06:16发布

In javascript how to convert sequence of numbers in an array to range of numbers?

eg. [2,3,4,5,10,18,19,20] to [2-5,10,18-20]

21条回答
Deceive 欺骗
2楼-- · 2020-01-30 07:11

I needed a PHP version that also supports downward ranges (e.g. [10,9,8] gets converted to [10-8]). So I have modified DisgruntledGoat's version who ported CMS's solution. It also handles Strings in the input properly.

function getRanges($nums)
{
    $ranges = array();

    for ($i = 0; $i < count($nums); $i++) {
        if (!is_numeric($nums[$i]) || !isset($nums[$i+1]) || !is_numeric($nums[$i+1])) {
            $ranges[] = $nums[$i];
            continue;
        }
        $rStart = $nums[$i];
        $rEnd = $rStart;
        $rDiff = $nums[$i+1] > $nums[$i] ? 1 : -1;
        while (isset($nums[$i+1]) && is_numeric($nums[$i+1]) && $nums[$i+1]-$nums[$i] == $rDiff)
            $rEnd = $nums[++$i];
        $ranges[] = $rStart == $rEnd ? $rStart : $rStart.'-'.$rEnd;
    }

    return $ranges;
}

Example:

getRanges([2,3,4,5,10,18,19,20,"downwards",10,9,8,7,6,5])
// Returns [2-5,10,18-20,"downwards",10-5]
查看更多
虎瘦雄心在
3楼-- · 2020-01-30 07:13

Very nice question: here's my attempt:

function ranges(numbers){
    var sorted = numbers.sort(function(a,b){return a-b;});
    var first = sorted.shift();
    return sorted.reduce(function(ranges, num){
        if(num - ranges[0][1] <= 1){
            ranges[0][1] = num;        
        } else {
            ranges.unshift([num,num]);
        }
        return ranges;
    },[[first,first]]).map(function(ranges){
        return ranges[0] === ranges[1] ? 
            ranges[0].toString() : ranges.join('-');
    }).reverse();
}

Demo on JSFiddler

查看更多
The star\"
4楼-- · 2020-01-30 07:14

In C#

    public string compressNumberRange(string inputSeq)
    {
        //Convert String array to long List and removing the duplicates
        List<long> longList = inputSeq.Split(',').ToList().ConvertAll<long>(s => Convert.ToInt64(s)).Distinct().ToList();

        //Sort the array
        longList.Sort();

        StringBuilder builder = new StringBuilder();


        for (int itr = 0; itr < longList.Count(); itr++)
        {
            long first = longList[itr];
            long end = first;

            while (longList[itr + 1] - longList[itr] == 1) //Seq check 
            {
                end = longList[itr + 1];
                itr++;
                if (itr == longList.Count() - 1)
                    break;
            }
            if (first == end) //not seq
                builder.Append(first.ToString() + ",");
            else //seq
                builder.Append(first.ToString() + "-" + end.ToString() + ",");
        }

        return builder.ToString();
    }
查看更多
登录 后发表回答