This question already has an answer here:
I am a newbie in PHP. I have been given the following as homework: Write a php function called findMissing that receives 3 parameters. The function must determine and return a missing number in an array of numbers – note: only one number will be missing from the series of numbers, the number you must find. All the numbers will be integers. ◦ $start : This will be an integer indicating the minimum number the array can contain. ◦ $end : This will be an integer indicating the maximum number the array can contain. ◦ $numbers : An array with numbers between $start and $end. This array might not be sorted. There is no guarantee that the first or last number in the array will correspond to $start and $end respectively. $start and $end are inclusive in the range of numbers As an example: findMissing(1, 5, array(2,5,1,3)); must return 4 as the missing number. The array $numbers will always contain $end - $start number of elements.
So far I have the following code:
function findMissing($start,$end,$numbers)
{
if ($start >0 && $end >0){
for ($x=0; $x<=end; $x++) {
$numbers=array($x);
}
}
foreach ($numbers as $value){
echo $value;
}
}
Please help because I am stuck
</div>
You may try this
<?php
$start = 1;
$end = 5;
$numbers = array(2,5,1,3);
findMissing($start,$end,$numbers);
function findMissing($start,$end,$numbers)
{
$range[$start-1] = 0; // here, it will be $range[0] = 0;
for($i=$start; $i<=$end; $i++)
{
$range[$i] = $range[$i-1]+1;
if(!in_array($range[$i], $numbers))
{
echo '<br> Missing no= '. $i;
//return $i;
}
}
}
?>
Hope this will be helpful...
When you are faced with a problem, and this is not just for programming, first thing first is you have to picture the solution in your head and see it working.
Given this task a few ideas come to mind:
You can sort the array and loop through it, as soon as a number that's not equal to the previous number + 1 occurs, you can safely say that previous number + 1
is your missing number.
Another way you can solve this is by looping in the range of $start
to $end
and check if each value is in the given array with in_array()
. As soon as you encounter a value that's not, needless to say, this is your number.
If your goal isn't to learn, but to just get rid of that homework, drop a comment I'll scribble the function for you.
dude!! here is a simple solution for that add all numbers between $start and $end as $sumAll and also add all the elements of that array as $sum now $missingNumber = $sumAll-$sum !! Do it it would be fun :)