-
-
Save alexruperez/22210062157502bf5aa975f81307b4c2 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
package challenge7 | |
val pairs = { map: String -> map.replace("[", "").replace("]", "").split(",").map { | |
val split = it.split("-") | |
Pair(split.first().single(), split.last().single()) | |
} } | |
val String.pairs get() = pairs(this) | |
val relatedWith = { relations: List<Pair<Char, Char>>, node: Char -> relations.filter { it.toList().contains(node) } } | |
fun List<Pair<Char, Char>>.relatedWith(node: Char) = relatedWith(this, node) | |
fun getCycles(relations: List<Pair<Char, Char>>, targetNode: Char, currentNode: Char, currentList: List<Char>): List<List<Char>> { | |
if (targetNode == currentNode) { | |
return listOf(currentList + targetNode) | |
} else if (!currentList.contains(currentNode)) { | |
return relations.relatedWith(currentNode).flatMap { getCycles(relations, targetNode, if (it.first == currentNode) it.second else it.first, currentList + currentNode) } | |
} | |
return emptyList() | |
} | |
val cyclesAround = { relations: List<Pair<Char, Char>> , targetNode: Char -> | |
relations.relatedWith(targetNode).flatMap { getCycles(relations, targetNode, if (it.first == targetNode) it.second else it.first, listOf(targetNode)) }.filter { it.count() > 3 } | |
} | |
fun List<Pair<Char, Char>>.cyclesAround(targetNode: Char): List<List<Char>> = cyclesAround(this, targetNode) | |
val join = { cycle: List<Char> -> cycle.joinToString("").toUpperCase() } | |
val List<Char>.join get() = join(this) | |
val joined = { cycles: List<List<Char>> -> cycles.map { it.join } } | |
val List<List<Char>>.joined get() = joined(this) | |
fun findingCycles(targetNode: Char, map: String) = map.pairs.cyclesAround(targetNode).joined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment