1
1
package aockt.y2015
2
2
3
+ import aockt.util.generatePermutations
3
4
import io.github.jadarma.aockt.core.Solution
4
5
5
6
object Y2015D09 : Solution {
6
7
7
- // The code for generating permutations is a slightly refactored version of Marcin Moskala's implementation,
8
- // because it's short and I want to keep dependencies to a minimum. Find the original at:
9
- // https://github.com/MarcinMoskala/KotlinDiscreteMathToolkit/blob/17a7329af042c5de232051027ec1155011d57da8/src/main/java/com/marcinmoskala/math/PermutationsExt.kt#L20
10
- // TODO: Make Util.
11
- private fun <T > List<T>.permutations (): Set <List <T >> = when (size) {
12
- 0 -> emptySet()
13
- 1 -> setOf (take(1 ))
14
- else -> drop(1 )
15
- .permutations()
16
- .flatMap { sublist -> (0 .. sublist.size).map { sublist.plusAt(it, first()) } }
17
- .toSet()
18
- }
19
-
20
- private fun <T > List<T>.plusAt (index : Int , element : T ): List <T > = when (index) {
21
- !in 0 .. size -> throw Error (" Cannot put at index $index because size is $size " )
22
- 0 -> listOf (element) + this
23
- size -> this + element
24
- else -> dropLast(size - index) + element + drop(index)
25
- }
26
-
27
8
private val inputRegex = Regex (""" ^(\w+) to (\w+) = (\d+)$""" )
28
9
29
10
/* * Parses a single line of input and returns a triple containing two locations and the distance between them. */
@@ -36,7 +17,7 @@ object Y2015D09 : Solution {
36
17
* Given a list of distances between all pairs of locations on the map, returns all possible paths that visit all
37
18
* of them and their total distance.
38
19
*/
39
- private fun bruteForceRoutes (locationData : List <Triple <String , String , Int >>): List <Pair <List <String >, Int>> {
20
+ private fun bruteForceRoutes (locationData : List <Triple <String , String , Int >>): Sequence <Pair <List <String >, Int>> {
40
21
val locations = mutableSetOf<String >()
41
22
val distances = mutableMapOf<Pair <String , String >, Int > ()
42
23
@@ -49,7 +30,7 @@ object Y2015D09 : Solution {
49
30
50
31
return locations
51
32
.toList()
52
- .permutations ()
33
+ .generatePermutations ()
53
34
.map { route -> route to route.windowed(2 ).sumOf { distances.getValue(it[0 ] to it[1 ]) } }
54
35
}
55
36
0 commit comments