Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找PHP中活着的人数最多的年份_Php_Date_Oop - Fatal编程技术网

查找PHP中活着的人数最多的年份

查找PHP中活着的人数最多的年份,php,date,oop,Php,Date,Oop,给出一份有出生和结束年份(都在1900年到2017年之间)的人的名单,找出活着人数最多的年份 <?php class Person { function __construct($birth, $death) { $this->birthYear = $birth; $this->deathYear = $death; } }; $people = [ new Person(1925, 1972),//47 new Person(1901,

给出一份有出生和结束年份(都在1900年到2017年之间)的人的名单,找出活着人数最多的年份

<?php
class Person {
    function __construct($birth, $death) {
    $this->birthYear = $birth;
    $this->deathYear = $death;
  }
};

$people = [
  new Person(1925, 1972),//47
  new Person(1901, 1960),//59
  new Person(1942, 1999),//57
  new Person(1960, 2010),//50
  new Person(1931, 2017),//86
  new Person(1961, 1995),//34
  new Person(1919, 1982),//63
];
$birth = array_column($people,"birthYear");
$death = array_column($people,"deathYear");
$START_YEAR = 1900;
$END_YEAR = 2017+1;
$people_alive = [];
$people = json_decode(json_encode($people),true);

foreach($people as $k=>$v){
    $a = $v['birthYear'] - $START_YEAR;
    $b = $v['deathYear'] - $START_YEAR +1;
    $people_alive[]= $b-$a +1;
}
print_r($people_alive);
我想要一个大多数人都活着的一年。
我对这种逻辑将如何产生感到困惑。

最简单的解决办法是,经过所有的岁月,计算一年中有多少人活着。然后,找出人数最多的一年——那将是活着人数最多的一年。请记住,此解决方案不是最优的,并且具有总体复杂性
O(n)


查看
array\u multisort
@Kyle谢谢你的建议,但我还是不知道这对memaybe有什么帮助,也许不会。我想我误解了这个问题。我的错。“我想要一年,其中……”如果有10年的时间是最大的活着人数,你在乎哪一年会回来吗?不,我不在乎。如果我能得到类似1925=>251950=>21等的列表,我会计算出在哪一年大多数人都活着,我想你的答案会有用的。我在查。太好了!谢谢@krlv。这就是我想要的
Array
(
    [0] => 49
    [1] => 61
    [2] => 59
    [3] => 52
    [4] => 88
    [5] => 36
    [6] => 65
)
<?php
class Person {
    public function __construct($birth, $death) {
        $this->birthYear = $birth;
        $this->deathYear = $death;
    }
};

$people = [
    new Person(1925, 1972),//47
    new Person(1901, 1960),//59
    new Person(1942, 1999),//57
    new Person(1960, 2010),//50
    new Person(1931, 2017),//86
    new Person(1961, 1995),//34
    new Person(1919, 1982),//63
];

$start = 1900;
$end = 2017;

// create list of years in given time frame
$years = array_fill($start, $end - $start + 1, 0);

// iterate through all the people
foreach ($people as $person) {
    for ($i = $person->birthYear; $i <= $person->deathYear; ++$i) {
        $years[$i] += 1;
    }
}

// the maximum number of people alive in one year
$max_count = max($years);
// the year with the most number of people alive
$max_year = array_search($max_count, $years);