-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrip.php
122 lines (100 loc) · 2.54 KB
/
trip.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
/**
* @description Trip category, creates trip according to trip cards
*
* @author Dusan Lukic <[email protected]>
*/
class Trip
{
private $points;
private $cards;
private $begin;
private $end;
private $moment; // current place
private $trip_end = true;
/**
* Sort cards.
*
* @param array $cards
*/
private function sort($cards)
{
while (true) {
foreach ($cards as $key => $val) {
// if start of the card is where we are, add card to stack
if ($val->start == $this->moment) {
// add to stack
$this->add($val);
// set new "moment" (current place) to destination of current card
$this->moment = $val->destination;
// remove this card
unset($cards[$key]);
}
}
// check if we reached the end of the trip
if ($this->end == $this->moment) {
return;
}
}
}
/**
* Determine global start and end and prepare starting moment.
*
* @param array $cards
*/
private function prepare($cards)
{
foreach ($cards as $key => $val) {
$destinations[] = $val->destination;
$starts[] = $val->start;
}
foreach ($destinations as $key => $val) {
if (!in_array($val, $starts)) {
$this->end = $val;
}
}
foreach ($starts as $key => $val) {
if (!in_array($val, $destinations)) {
$this->begin = $val;
}
}
// set current place to beginning
$this->moment = $this->begin;
}
/**
* Add card to current points stack.
*
* @param Card $card
*/
private function add(Card $card)
{
$this->points[] = $card;
}
/**
* Output final string.
*
* @return string
*/
private function output()
{
foreach ($this->points as $key => $val) {
$stack[] = "Take " . $val->transportation . " from " . $val->start . " to " . $val->destination .
". The seat is: " . $val->seat;
}
$final = implode("\n", $stack);
return $final;
}
/**
* Initialize.
*
* @param array $cards
*
* @return string
*/
public function init($cards)
{
$this->prepare($cards);
$this->sort($cards);
return $this->output();
}
}