This code will accept user input from the command line.
The first user can enter the limit of series.
e.g: user may enter 5
After that, the user will be prompted for 5 numbers of a series.
e.g:
2 4 8 10 12
Here in this series, 6 is missing, so I am going to find the missing series from common difference series.
I got the correct output from this code. Is it the correct way? Is there any other simple code to do the same?
<?php
fscanf(STDIN, "%d\n", $count);
$series = array();
$common_diff = array();
$prev_element = null;
for($i=0;$i<$count;$i++){
fscanf(STDIN, "%d\n", $series[$i]);
if($prev_element != null){
$common_diff[] = $series[$i] - $prev_element;
}
$prev_element = $series[$i];
}
$c = array_count_values($common_diff);
asort($c);
end($c);
$common_d = key($c);
$prev_element = $series[0];
$missed_no = 0;
for($i=1;$i<$count;$i++){
$diff = $series[$i] - $prev_element;
if($diff != $common_d){
$missed_no = $prev_element + $common_d;
}
$prev_element = $series[$i];
}
echo $missed_no;
exit;
?>
example input
5 2 4 8 10 12