Created
December 9, 2015 12:04
-
-
Save AntonFagerberg/c9aaee45209f1c946896 to your computer and use it in GitHub Desktop.
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
val input = """Tristram to AlphaCentauri = 34 | |
Tristram to Snowdin = 100 | |
Tristram to Tambi = 63 | |
Tristram to Faerun = 108 | |
Tristram to Norrath = 111 | |
Tristram to Straylight = 89 | |
Tristram to Arbre = 132 | |
AlphaCentauri to Snowdin = 4 | |
AlphaCentauri to Tambi = 79 | |
AlphaCentauri to Faerun = 44 | |
AlphaCentauri to Norrath = 147 | |
AlphaCentauri to Straylight = 133 | |
AlphaCentauri to Arbre = 74 | |
Snowdin to Tambi = 105 | |
Snowdin to Faerun = 95 | |
Snowdin to Norrath = 48 | |
Snowdin to Straylight = 88 | |
Snowdin to Arbre = 7 | |
Tambi to Faerun = 68 | |
Tambi to Norrath = 134 | |
Tambi to Straylight = 107 | |
Tambi to Arbre = 40 | |
Faerun to Norrath = 11 | |
Faerun to Straylight = 66 | |
Faerun to Arbre = 144 | |
Norrath to Straylight = 115 | |
Norrath to Arbre = 135 | |
Straylight to Arbre = 127""" | |
val distances = | |
input.split("\n") | |
.map(_.split("( to | = )")) | |
.flatMap(a => | |
List ( | |
(a(0) -> a(1)) -> a(2).toInt, | |
(a(1) -> a(0)) -> a(2).toInt | |
) | |
).toMap | |
val allPlaces = distances.keys.toList.map(_._1).distinct | |
def recMin(currentDestination: String, remainingDestinations: List[String], distance: Int = 0): Int = { | |
if (remainingDestinations.isEmpty) { | |
distance | |
} else { | |
remainingDestinations.map { nextDestination => | |
recMin(nextDestination, remainingDestinations.filter(_ != nextDestination), distance + distances(currentDestination -> nextDestination)) | |
}.min | |
} | |
} | |
def recMax(currentDestination: String, remainingDestinations: List[String], distance: Int = 0): Int = { | |
if (remainingDestinations.isEmpty) { | |
distance | |
} else { | |
remainingDestinations.map { nextDestination => | |
recMax(nextDestination, remainingDestinations.filter(_ != nextDestination), distance + distances(currentDestination -> nextDestination)) | |
}.max | |
} | |
} | |
val min = allPlaces.map(destination => recMin(destination, allPlaces.filter(_ != destination))).min | |
val max = allPlaces.map(destination => recMax(destination, allPlaces.filter(_ != destination))).max |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment