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 $ft): PeopleComparison |
18
|
|
|
{ |
19
|
|
|
/** @var PeopleComparison[] $tr */ |
20
|
6 |
|
$tr = []; |
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->setFirstPerson($first_person); |
31
|
3 |
|
$current_people_comparison->setSecondPerson($second_person); |
32
|
|
|
} else { |
33
|
3 |
|
$current_people_comparison->setFirstPerson($second_person); |
34
|
3 |
|
$current_people_comparison->setSecondPerson($first_person); |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
$current_people_comparison->setBirthdayDifference($current_people_comparison->secondPerson()->birthDate()->getTimestamp() |
38
|
4 |
|
- $current_people_comparison->firstPerson()->birthDate()->getTimestamp()); |
39
|
|
|
|
40
|
4 |
|
$tr[] = $current_people_comparison; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
6 |
|
if (empty($tr)) { |
45
|
2 |
|
return new PeopleComparison(); |
46
|
|
|
} |
47
|
|
|
|
48
|
4 |
|
$answer = $tr[0]; |
49
|
|
|
|
50
|
4 |
|
foreach ($tr as $result) { |
51
|
|
|
switch ($ft) { |
52
|
4 |
|
case FT::ONE: |
53
|
2 |
|
if ($result->birthdayDifference() < $answer->birthdayDifference()) { |
54
|
1 |
|
$answer = $result; |
55
|
|
|
} |
56
|
2 |
|
break; |
57
|
|
|
|
58
|
2 |
|
case FT::TWO: |
59
|
2 |
|
if ($result->birthdayDifference() > $answer->birthdayDifference()) { |
60
|
|
|
$answer = $result; |
61
|
|
|
} |
62
|
4 |
|
break; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
4 |
|
return $answer; |
67
|
|
|
} |
68
|
|
|
|
69
|
4 |
|
private function isFirstPersonMoreYoungerThanSecondPerson($first_person_index, $second_person_index): bool |
70
|
|
|
{ |
71
|
4 |
|
return $this->people[$first_person_index]->birthDate() < $this->people[$second_person_index]->birthDate(); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
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: