Created
April 19, 2018 21:08
-
-
Save arthurdenner/563ff5d0d14088ae35c0d686b8fdb7f6 to your computer and use it in GitHub Desktop.
Busca Gulosa - Arthur Denner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const map = { | |
iasi: [ | |
{ city: 'neamt', distance: 87 }, | |
{ city: 'vaslui', distance: 92 }, | |
], | |
vaslui: [ | |
{ city: 'urziceni', distance: 142 }, | |
{ city: 'iasi', distance: 92 }, | |
], | |
urziceni: [ | |
{ city: 'hirsova', distance: 98 }, | |
{ city: 'bucharest', distance: 85 }, | |
], | |
bucharest: [ | |
{ city: 'giurgiu', distance: 90 }, | |
{ city: 'fagaras', distance: 211 }, | |
{ city: 'pitesti', distance: 101 }, | |
], | |
pitesti: [ | |
{ city: 'craiova', distance: 138 }, | |
{ city: 'rimnicu', distance: 97 }, | |
{ city: 'bucharest', distance: 101 }, | |
], | |
rimnicu: [ | |
{ city: 'sibiu', distance: 80 }, | |
{ city: 'pitesti', distance: 97 }, | |
{ city: 'craiova', distance: 146 }, | |
], | |
sibiu: [ | |
{ city: 'fagaras', distance: 99 }, | |
{ city: 'oradea', distance: 151 }, | |
{ city: 'arad', distance: 140 }, | |
{ city: 'rimnicu', distance: 80 }, | |
], | |
fagaras: [ | |
{ city: 'bucharest', distance: 211 }, | |
{ city: 'sibiu', distance: 99 }, | |
] | |
}; | |
const getShortestWay = (cityParam, destiny, cameFrom) => { | |
console.log('---------'); | |
if (cityParam === destiny) { | |
return console.log('arrived in ', cityParam); | |
} | |
const city = map[cityParam]; | |
if (!city) { | |
console.log('going back to', cameFrom); | |
return getShortestWay(cameFrom, destiny, cityParam); | |
} | |
const [closest, second] = city.sort((a, b) => a.distance > b.distance ? 1 : -1); | |
console.log('cityParam', cityParam); | |
console.log('closest', closest); | |
console.log('cameFrom', cameFrom); | |
if (!map[closest.city] || closest.city === cameFrom) { | |
if (!map[closest.city]) { | |
console.log('there is no map to', closest.city); | |
} | |
console.log('going to ', second.city); | |
return getShortestWay(second.city, destiny, cityParam); | |
} | |
console.log('going to ', closest.city); | |
return getShortestWay(closest.city, destiny, cityParam); | |
} | |
getShortestWay('iasi', 'fagaras'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment