开发者

Add to array consecutive numbers

开发者 https://www.devze.com 2023-01-25 19:56 出处:网络
This is my first question to SO, I hope to get it right. In PHP (if you can\'t, python or pseudo language is also okay), Given an array of n elements:

This is my first question to SO, I hope to get it right. In PHP (if you can't, python or pseudo language is also okay), Given an array of n elements:

old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]

I need to add to a new array consecutive numbers, if it is not a consecutive number add only that value to a new array:

new_array = [ [1,2,3],
              [5],
              [7,8,9]
              [20,21]
          开发者_如何学编程    [23],
              [29]
            ]

Here on SO, i found these related topics, but can't get it to work.

  1. Creating a list of lists with consecutive numbers
  2. Python finding n consecutive numbers in a list
  3. Find the sum of consecutive whole numbers w/o using loop in JavaScript

The code that wasn't working is on the version history, I removed it because it's having formatting problems.

Thanks all, and especially Juan, mistabell and Axsuul for the providing the correct answer.


The best I can came up with is:

function subsequenceArray($values) {
    $res = array();
    $length = count($values);
    if (0 == $length) {
        return $res;
    }
    $last = 0;
    $res[$last] = array($values[0]);
    for ($i = 1; $i < $length; $i++) {
        if ($values[$i] == $values[$i-1] + 1) {
            $res[$last][] = $values[$i];
        } else {
            $res[++$last] = array($values[$i]);
        }
    }
    return $res;
}


Try this

function buildPairedArray($oldArray) {
$newArray = array();
$i = 0;

foreach ($oldArray as $index => $value) {
    if ($index == 0) {
        $newArray[$i][] = $value;
        continue;

    }

    if ($oldArray[$index] == $oldArray[$index-1]+1) { // consecutive
        $newArray[$i][] = $value;

    } else {
        $newArray[++$i][] = $value;

    }
}

return $newArray;

}

Testing it

$old = array(1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29);
print_r(buildPairedArray($old));

Results:

Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 )

[1] => Array
    (
        [0] => 5
    )

[2] => Array
    (
        [0] => 7
        [1] => 8
        [2] => 9
    )

[3] => Array
    (
        [0] => 20
        [1] => 21
    )

[4] => Array
    (
        [0] => 23
    )

[5] => Array
    (
        [0] => 29
    )

)


Agreed, feels like a standard algorithm design question to me. Eagleal, have you tried thinking through the psuedo-code for this, and then converting that to PHP? How would you tell mathematically (in your head) if two given numbers are consecutive? Hint: The answer involves subtraction, or even addition, and the number 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号