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条回答
干净又极端
2楼-- · 2020-01-30 06:47
 ; For all cells of the array
    ;if current cell = prev cell + 1 -> range continues
    ;if current cell != prev cell + 1 -> range ended

int[] x  = [2,3,4,5,10,18,19,20]
string output = '['+x[0]
bool range = false; --current range
for (int i = 1; i > x[].length; i++) {
  if (x[i+1] = [x]+1) {
    range = true;
  } else { //not sequential
  if range = true
     output = output || '-' 
  else
     output = output || ','
  output.append(x[i]','||x[i+1])
  range = false;
  } 

}

Something like that.

查看更多
beautiful°
3楼-- · 2020-01-30 06:53

Here's my take on this...

function getRanges(input) {

  //setup the return value
  var ret = [], ary, first, last;

  //copy and sort
  var ary = input.concat([]);
  ary.sort(function(a,b){
    return Number(a) - Number(b);
  });

  //iterate through the array
  for (var i=0; i<ary.length; i++) {
    //set the first and last value, to the current iteration
    first = last = ary[i];

    //while within the range, increment
    while (ary[i+1] == last+1) {
      last++;
      i++;
    }

    //push the current set into the return value
    ret.push(first == last ? first : first + "-" + last);
  }

  //return the response array.
  return ret;
}
查看更多
【Aperson】
4楼-- · 2020-01-30 06:54

PHP

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

for ( $i = 0, $len = count($nums); $i < $len; $i++ )
{
    $rStart = $nums[$i];
    $rEnd = $rStart;
    while ( isset($nums[$i+1]) && $nums[$i+1]-$nums[$i] == 1 )
        $rEnd = $nums[++$i];

    $ranges[] = $rStart == $rEnd ? $rStart : $rStart.'-'.$rEnd;
}

return $ranges;
}


echo print_r(getRanges(array(2,21,3,4,5,10,18,19,20)));
echo print_r(getRanges(array(1,2,3,4,5,6,7,8,9,10)));
查看更多
虎瘦雄心在
5楼-- · 2020-01-30 06:56

I've written my own method that's dependent on Lo-Dash, but doesn't just give you back an array of ranges, rather, it just returns an array of range groups.

[1,2,3,4,6,8,10] becomes:

[[1,2,3,4],[6,8,10]]

http://jsfiddle.net/mberkom/ufVey/

查看更多
时光不老,我们不散
6楼-- · 2020-01-30 06:57

If you simply want a string that represents a range, then you'd find the mid-point of your sequence, and that becomes your middle value (10 in your example). You'd then grab the first item in the sequence, and the item that immediately preceded your mid-point, and build your first-sequence representation. You'd follow the same procedure to get your last item, and the item that immediately follows your mid-point, and build your last-sequence representation.

// Provide initial sequence
var sequence = [1,2,3,4,5,6,7,8,9,10];
// Find midpoint
var midpoint = Math.ceil(sequence.length/2);
// Build first sequence from midpoint
var firstSequence = sequence[0] + "-" + sequence[midpoint-2];
// Build second sequence from midpoint
var lastSequence  = sequence[midpoint] + "-" + sequence[sequence.length-1];
// Place all new in array
var newArray = [firstSequence,midpoint,lastSequence];

alert(newArray.join(",")); // 1-4,5,6-10

Demo Online: http://jsbin.com/uvahi/edit

查看更多
神经病院院长
7楼-- · 2020-01-30 06:57
import java.util.ArrayList;
import java.util.Arrays;



public class SequencetoRange {

    /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

        int num[] = {1,2,3,63,65,66,67,68,69,70,80,90,91,94,95,4,101,102,75,76,71};

        int l = num.length;
        int i;
        System.out.print("Given number : ");
        for (i = 0;i < l;i++ ){
            System.out.print("  " + num[i]);
        }
        System.out.println("\n");
        Arrays.sort(num);

        ArrayList newArray = new ArrayList();
        newArray = getRanges(num);
        System.out.print("Range : ");
        for(int y=0;y<newArray.size();y++)
        {
            System.out.print(" " +newArray.get(y));
        }
    }

    public static ArrayList getRanges(int num[])
    {  
        ArrayList ranges = new ArrayList();
        int rstart, rend;   
        int lastnum = num[num.length-1];
        for (int i = 0; i < num.length-1; i++) 
        {     
            rstart = num[i];     
            rend = rstart;     
            while (num[i + 1] - num[i] == 1) 
            {       
                rend = num[i + 1]; 
                // increment the index if the numbers sequential       
                if(rend>=lastnum)
                {
                    break;
                }
                else
                {
                    i++;
                }  
            }  
            if(rstart==rend)
            {
                ranges.add(rend);
            }
            else
            {
                ranges.add(+rstart+"..."+rend);
            }
        } 
        return ranges; 
    } 
}
查看更多
登录 后发表回答