Out of sequence numbers

Discussion in 'PHP' started by webboy, Nov 12, 2009.

  1. #1
    Hi all I have a set of numbers in order and wish to check if they are out sequence then display the range of numbers which are missing


    input = 1,2,3,4,8

    should output 5 6 7 or 5 > 7
    what whould i need to do in php to get the output ?
     
    webboy, Nov 12, 2009 IP
  2. CreativeClans

    CreativeClans Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    $input = '2,3,4,8';
    $numbers = explode(',', $input);
    $check = 0;
    for ($i = 1; $i <= $numbers[count($numbers) - 1]; $i++) {
      if ($numbers[$check] < $i) $check++;
      if ($numbers[$check] > $i) echo "$i ";
    }
    
    PHP:
    Should (didn't test it) output:
    1 5 6 7
     
    CreativeClans, Nov 12, 2009 IP
  3. yourlistonline

    yourlistonline Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    If you put the numbers into an array, why not just asort the array?

    
    $numbers = "1,4,7,2,14";
    $sort = explode(",",$numbers);
    asort($sort);
    foreach($sort as $number) {
        print $number."<br />";
    }
    
    PHP:
    Should output...
    1
    2
    4
    7
    14
     
    yourlistonline, Nov 12, 2009 IP
  4. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #4
    <?php
    
    /**
     * @author Jay Gilford
     */
    
    $input = '2,4,6,8,16,18,20,28';
    
    $arr = explode(',', $input);
    sort($arr);
    
    $out = array();
    $array_items = count($arr);
    $lower = $arr[0];
    $upper = $arr[$array_items - 1];
    
    $difference = $upper;
    
    for($i = 1; $i < $array_items; $i++) {
        $diff = $arr[$i] - $arr[$i - 1];
        if($diff < $difference) $difference = $diff;
    }
    
    for($i = $lower; $i < $upper; $i += $difference) {
        if(in_array($i,$arr) === false) $out[] = $i;
    }
    echo '<pre>'.print_r($out, true).'</pre>';
    PHP:
    This will work out the lowest difference between items and find the missing elements and store them in the array $out

    @yourlistonline - He's already got the numbers in order, he's trying to find the missing numbers in the sequence
     
    JAY6390, Nov 12, 2009 IP