如何找到集合中三个连续值之和等于某个值的频率?

9 numbers. Count how often the sum of 3 consecutive numbers in this set of numbers equaled to 16: 2, 7, 7, 1, 8, 2, 7, 8, 7,

The answer is 2. 2 + 7 + 7 = 16 and 7 + 1 + 8 = 16

But I can't seem to get the answer, because I don't know how to "loop" back and skip the first number and do the process over.

How would one be able to solve this utilizing arrays, and how would one solve this without utilizing arrays?

The 9 numbers are randomly generated, and it has to stay that way, but for the sake of solving, I used seed of 3 using srand(3). This is my current code below:

<?php
srand(3);

$count = 1;
$answer = 0;

$num1 = 0;
$num2 = 0;
$num3 = 0;

for ($i = 0; $i < 9; $i++)
{
    $num = rand(0, 9);

    echo $num . ', ';

    if ($count == 1)
        $num1 = $num;
    else if ($count == 2)
        $num2 = $num;
    else if ($count == 3)
    {
        $num3 = $num;
        $count = 1;
    }

    if ($num1 + $num2 + $num3 == 16)
        $answer++;

    $count++;
}

echo '<br />*******' . $answer . '*******';
?>

Obviously this isn't the right answer because I had to do the check again, but skipping the first number, and so on and so forth until (the last indexed number - index 3)

Not a PHP writer but this could be your approach:

  1. Fill the array from indices 0 up to and including 8 with a random value.
  2. Iterate from index 0 to index [length - 3]. (length is 9)
  3. Calculate the sum of the values on index [currentIndex], [currentIndex + 1] and [currentIndex + 2].
  4. Whenever the value of that sum equals 16, increment your [count] variable by 1.

Probably not the most efficient solution, but its hard to think at 11 at night:

$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array);
for ($x = 0; $x < $count; $x++) {
    $parts = array_chunk($array, 3);
    foreach ($parts as $part) {
        if (array_sum($part) == 16 && count($part) == 3) {
            print_r($part);
        }
    }
    array_shift($array);
}

Another solution which I think is the more efficient, logic similar to what @Jeroen Vannevel answered:

$array = array(2, 7, 7, 1, 8, 2, 7, 8, 7);
$count = count($array) - 2;

for ($x = 0; $x < $count; $x++) {
    if ($array[$x] + $array[$x+1] + $array[$x+2] == 16) {
        echo "{$array[$x]} + {$array[$x+1]} + {$array[$x+2]} = 16 <br />";
    }
}