/
3.php
101 lines (86 loc) · 2.6 KB
/
3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
class PresentDeliverer
{
/** @var array */
protected $presentCount = [];
/** @var array */
protected $positions = [];
/** @var array */
protected $persons = [];
public function __construct($persons = [])
{
$this->persons = $persons;
$this->reset();
}
/**
* @param $route
* @return array
*/
public function doDelivery($route)
{
$this->reset();
foreach ($this->persons as $person) {
$this->deliverPresent($person);
}
foreach (str_split($route) as $i => $command) {
if (count($this->persons) == 1) {
$personToAct = $this->persons[0];
} else {
$personToAct = $this->persons[$i % 2 == 0 ? 1 : 0];
}
$this->move($command, $personToAct);
$this->deliverPresent($personToAct);
}
return $this->presentCount;
}
protected function reset()
{
foreach ($this->persons as $person) {
$this->positions[$person] = [0, 0];
}
$this->presentCount = [];
}
/**
* @param string $command
* @param string $who
*/
protected function move($command, $who) {
switch ($command) {
case '^':
$this->positions[$who][1]--;
break;
case 'v':
$this->positions[$who][1]++;
break;
case '>':
$this->positions[$who][0]++;
break;
case '<':
$this->positions[$who][0]--;
break;
}
}
/**
* Delivers a present at the current position on the grid
*/
private function deliverPresent($who)
{
$position = $this->positions[$who];
$key = implode(':', $position);
if (!isset($this->presentCount[$key])) {
$this->presentCount[$key] = 0;
}
$this->presentCount[$key]++;
}
}
$input = file_get_contents('3.txt');
$presentDeliverer1 = new PresentDeliverer(['santa']);
$presentDeliverer2 = new PresentDeliverer(['santa', 'robo']);
/*print_r($presentDeliverer1->doDelivery('>'));
print_r($presentDeliverer1->doDelivery('^>v<'));
print_r($presentDeliverer1->doDelivery('^v^v^v^v^v'));
print_r($presentDeliverer2->doDelivery('^v'));
print_r($presentDeliverer2->doDelivery('^>v<'));
print_r($presentDeliverer2->doDelivery('^v^v^v^v^v'));*/
echo sprintf('Part 1 answer: %s', count($presentDeliverer1->doDelivery($input))) . PHP_EOL;
echo sprintf('Part 2 answer: %s', count($presentDeliverer2->doDelivery($input))) . PHP_EOL;