我需要一个问题的帮助,我需要在php中编写代码
示例数字序列,$ sequence = 3,5,9,11,13 很明显数字7丢失了,但我不知道怎么做代码,我假设它会使用循环,但我甚至不知道要开始,它必须在PHP
答案 0 :(得分:0)
<?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 )
?>
答案 1 :(得分:0)
仅使用前三个元素来查找间隔(需要3个匹配中的2个),并且不验证序列的其余部分是否遵循规则,还会发现更多缺少的元素:
<?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));
答案 2 :(得分:0)
从序列中获取缺失数字的更简单方法,就像我看到的那样:
<?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);
?>