एरे में पहले 'n' मिसिंग नंबर ढूंढना
उदाहरण
<?php
function missing_values($my_arr, $len, $n) {
sort($my_arr);
// नोट: sort($my_arr, $len) गलत है, sort दूसरा पैरामीटर फ्लैग लेता है
$i = 0;
while ($i < $n && $my_arr[$i] <= 0) {
$i++;
}
$count = 0;
$curr = 1;
while ($count < $n && $i < $len) {
if ($my_arr[$i] != $curr) {
echo $curr . " ";
$count++;
} else {
$i++;
}
$curr++;
}
while ($count < $n) {
echo $curr . " ";
$curr++;
$count++;
}
}
$my_arr = array(6, 8, 0);
$len = sizeof($my_arr);
$n = 5;
print_r("The missing values of the array are ");
missing_values($my_arr, $len, $n);
?>
आउटपुट
The missing values of the array are 1 2 3 4 5
कोड विश्लेषण और सुधार
मूल कोड में कुछ समस्याएं हैं:
sort($my_arr, $len)- sort का दूसरा पैरामीटर सॉर्ट फ्लैग होता है, लंबाई नहीं।$nऔर$kवेरिएबल मिक्स हैं।- नेगेटिव नंबर्स हैंडल नहीं किए गए।
सुधारा गया संस्करण
<?php
function findMissingNumbers(array $arr, int $count): array {
// पॉजिटिव नंबर्स को फिल्टर और सॉर्ट करें
$positive = array_filter($arr, fn($x) => $x > 0);
sort($positive);
$positive = array_values($positive); // री-इंडेक्स
$missing = [];
$current = 1;
$index = 0;
$len = count($positive);
while (count($missing) < $count) {
if ($index < $len && $positive[$index] == $current) {
// नंबर एरे में मौजूद है
$index++;
// डुप्लीकेट्स स्किप करें
while ($index < $len && $positive[$index] == $current) {
$index++;
}
} else {
// नंबर मिसिंग है
$missing[] = $current;
}
$current++;
}
return $missing;
}
$my_arr = [6, 8, 0, -1, 2, 2];
$missing = findMissingNumbers($my_arr, 5);
echo "Missing: " . implode(" ", $missing);
// आउटपुट: Missing: 1 3 4 5 7
?>
मुख्य सुधार
- टाइप हिंट्स और रिटर्न टाइप जोड़े गए
- नेगेटिव नंबर्स और डुप्लीकेट्स हैंडल किए गए
- एरे के बजाय मानों की सरणी लौटाता है (अधिक उपयोगी)
- क्लीनर लॉजिक और वेरिएबल नाम