<?php
$people = [
[1801, 1887],
[1943, 1943],
[1949, 2001],
[1751, 1803],
[1881, 1887],
[1956, 1983],
[1954, 1983],
[1801, 1883],
[1956, null],
[1944, 1983],
[1897, 2015],
[1965, 1997],
[1941, 1982],
[1984, null],
];
$populationPerYear = array_reduce(
$people,
static function($carry, $current) {
[$from, $to] = $current;
for($i = $from; $i <= $to; $i++) {
if (!isset($carry[$i])) {
$carry[$i] = 1;
} else {
$carry[$i]++;
}
}
return $carry;
},
[]
);
ksort($populationPerYear);
$peak = max($populationPerYear);
$peakYears = array_filter(
$populationPerYear,
static function($population) use ($peak) {
return $population === $peak;
}
);
var_dump($peak, $peakYears);
- Output for 7.1.25 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
- int(7)
array(18) {
[1965]=>
int(7)
[1966]=>
int(7)
[1967]=>
int(7)
[1968]=>
int(7)
[1969]=>
int(7)
[1970]=>
int(7)
[1971]=>
int(7)
[1972]=>
int(7)
[1973]=>
int(7)
[1974]=>
int(7)
[1975]=>
int(7)
[1976]=>
int(7)
[1977]=>
int(7)
[1978]=>
int(7)
[1979]=>
int(7)
[1980]=>
int(7)
[1981]=>
int(7)
[1982]=>
int(7)
}
preferences:
190.25 ms | 404 KiB | 183 Q