Вопрос

i need help with a question, I need to write code in php that will

  • find the missing number in the sequence, regardless of that numbers position in the sequence.
  • the numbers will increase but the same amount each time.
  • the output must be only the number that was missing from the initial list, not just the list with the number in it (I have worked that out myself).

example number sequence, $sequence = 3, 5, 9, 11, 13 obviously the number 7 is missing, but I don't know how to do the code, im assuming it would use loops, but i wouldn't even know were to start, It must be in PHP

Это было полезно?

Решение

A more simple way to get the missing number(s) from the sequence, the way I see it:

<?php
    $sequence = array(3, 5, 9, 11, 13);
    $numbers = array(7, 9, 15);
    $single_nr = 7;
    function getMissingNumber(array $sequence, $single_nr = null, $numbers = array())
    {
        // Check if it exists in the sequence array
        // check single number
        if($single_nr)
        {
            if(!in_array($single_nr, $sequence))
            {
                echo $single_nr . " is not in array" . "<br />";
            }
        }

        // check an array of numbers
        if($numbers)
        {
            foreach($numbers as $nr)
            {
                if(!in_array($nr, $sequence))
                {
                    echo $nr . " is not in array" . "<br />";
                }
            }
        }
    }

    echo getMissingNumber($sequence, null, $numbers);
?>

Другие советы

Only uses the first three elements to find the interval (needs a 2 out of 3 match) and doesn't validate if the rest of the sequence follow the rule, but also finds more missing elements:

<?php

$sequence = array(3, 5, 9, 13, 15, 17, 21);

// guess
$step = $sequence[1] - $sequence[0];
// validate
if (($sequence[2] - $sequence[1]) != $step) {
    if (($sequence[3] - $sequence[2]) != $step) {
        $step = $sequence[2] - $sequence[1];
        if (($sequence[3] - $sequence[2]) != $step) {
            die('first three intervals are all different');
        }
    }
}

$should = range($sequence[0], $sequence[count($sequence) - 1], $step);
echo 'Missing: ', implode(', ', array_diff($should, $sequence));
 <?php
$str="3,5,9,11,13" ;
$arr=explode(',', $str);
$no=array();
for ($i=3; $i <30 ; $i=$i+2) { 
    $m=$i+2;
    if (!(in_array($m, $arr)))
  {
  $no[]=$m;
  }
    }



    print_r($no);
// OUTPUT- Array ( [0] => 7 [1] => 15 )
     ?>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top