1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Kata\Algorithm; |
6
|
|
|
|
7
|
|
|
final class Finder |
8
|
|
|
{ |
9
|
|
|
/** @var Person[] */ |
10
|
|
|
private $people; |
11
|
|
|
|
12
|
6 |
|
public function __construct(array $a_people) |
13
|
|
|
{ |
14
|
6 |
|
$this->people = $a_people; |
15
|
6 |
|
} |
16
|
|
|
|
17
|
6 |
|
public function find(int $birthday_sort): PeopleComparison |
18
|
|
|
{ |
19
|
|
|
/** @var PeopleComparison[] $people_comparisons */ |
20
|
6 |
|
$people_comparisons = []; |
21
|
|
|
|
22
|
6 |
|
for ($i = 0; $i < count($this->people); $i++) { |
|
|
|
|
23
|
5 |
|
for ($j = $i + 1; $j < count($this->people); $j++) { |
|
|
|
|
24
|
4 |
|
$current_people_comparison = new PeopleComparison(); |
25
|
|
|
|
26
|
4 |
|
$first_person = $this->people[$i]; |
27
|
4 |
|
$second_person = $this->people[$j]; |
28
|
|
|
|
29
|
4 |
|
if ($this->isFirstPersonMoreYoungerThanSecondPerson($i, $j)) { |
30
|
3 |
|
$current_people_comparison->setYoungPerson($first_person); |
31
|
3 |
|
$current_people_comparison->setOldPerson($second_person); |
32
|
|
|
} else { |
33
|
3 |
|
$current_people_comparison->setYoungPerson($second_person); |
34
|
3 |
|
$current_people_comparison->setOldPerson($first_person); |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
$people_comparisons[] = $current_people_comparison; |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
6 |
|
if (empty($people_comparisons)) { |
42
|
2 |
|
return new PeopleComparison(); |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
return $this->getPeopleComparisonWith($birthday_sort, $people_comparisons); |
46
|
|
|
} |
47
|
|
|
|
48
|
4 |
|
private function isFirstPersonMoreYoungerThanSecondPerson($first_person_index, $second_person_index): bool |
49
|
|
|
{ |
50
|
4 |
|
return $this->people[$first_person_index]->birthDate() < $this->people[$second_person_index]->birthDate(); |
51
|
|
|
} |
52
|
|
|
|
53
|
4 |
|
private function getPeopleComparisonWith(int $birthday_sort, array $people_comparisons) |
54
|
|
|
{ |
55
|
4 |
|
$answer = $people_comparisons[0]; |
56
|
|
|
|
57
|
4 |
|
foreach ($people_comparisons as $result) { |
58
|
|
|
switch ($birthday_sort) { |
59
|
4 |
|
case BirthdaySort::CLOSEST: |
60
|
2 |
|
if ($result->birthdayDifference() < $answer->birthdayDifference()) { |
61
|
1 |
|
$answer = $result; |
62
|
|
|
} |
63
|
2 |
|
break; |
64
|
|
|
|
65
|
2 |
|
case BirthdaySort::FURTHEST: |
66
|
2 |
|
if ($result->birthdayDifference() > $answer->birthdayDifference()) { |
67
|
|
|
$answer = $result; |
68
|
|
|
} |
69
|
4 |
|
break; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
4 |
|
return $answer; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: