8000 added solution to find route for itineries · dotmarn/algorithm-solution@93e0252 · GitHub
[go: up one dir, main page]

Skip to content

Commit 93e0252

Browse files
committed
added solution to find route for itineries
1 parent 33ce858 commit 93e0252

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

Find Route/index.php

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
function find_from($routes, $dest)
3+
{
4+
$from = null;
5+
foreach ($routes as $key => $value) {
6+
if ($value[1] == $dest) {
7+
$from = $value[0];
8+
}
9+
}
10+
return $from;
11+
}
12+
13+
function find_dest($routes, $from)
14+
{
15+
$dest = null;
16+
foreach ($routes as $key => $value) {
17+
if ($value[0] == $from) {
18+
$dest = $value[1];
19+
}
20+
}
21+
return $dest;
22+
}
23+
24+
function find_routes(array $routes): string
25+
{
26+
$output = [];
27+
28+
if (sizeof($routes) == 0) {
29+
return $output;
30+
}
31+
32+
$firstFrom = null;
33+
$from = $routes[0][0];
34+
$dest = null;
35+
$counter = 0;
36+
do {
37+
$firstFrom = find_from($routes, $from);
38+
if ($firstFrom != null) {
39+
$from = $firstFrom;
40+
}
41+
$counter++;
42+
} while ($firstFrom != null && $counter < sizeof($routes));
43+
44+
array_push($output, $from);
45+
46+
$counter = 0;
47+
do {
48+
$dest = find_dest($routes, $from);
49+
if ($dest != null) {
50+
array_push($output, $dest);
51+
$from = $dest;
52+
}
53+
$counter++;
54+
} while ($dest != null && $counter < sizeof($routes));
55+
56+
return implode(", ", $output);
57+
}

Find Route/question.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
### Task
2+
We are tracking down our rogue agent and she travels from place to place to avoid being tracked. Each of her travels are based on a list of itineraries in an unusual or incorrect order. The task is to determine the complete route she will take.
3+
4+
You are given an array of `routes` containing her travel itineraries. Convert this into a complete, in-order list of the places she will travel.
5+
6+
### Specification
7+
8+
### findRoutes(routes)
9+
10+
### Parameters
11+
- routes: Array<Array<String>> - Array of itineraries
12+
### Return Value
13+
- String - An ordered list or destinations
14+
### Constraints
15+
- All inputs have at least one valid, complete route
16+
### Examples
17+
#### routes #### Return Value
18+
```
19+
[["USA","BRA"],["JPN","PHL"],["BRA","UAE"],["UAE","JPN"]] "USA, BRA, UAE, JPN, PHL"
20+
```

0 commit comments

Comments
 (0)
0