Skip to content

Instantly share code, notes, and snippets.

@alexruperez
Created March 4, 2018 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexruperez/22210062157502bf5aa975f81307b4c2 to your computer and use it in GitHub Desktop.
Save alexruperez/22210062157502bf5aa975f81307b4c2 to your computer and use it in GitHub Desktop.
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