From 009689b294116311bbed8824b32352a7a8f986f4 Mon Sep 17 00:00:00 2001 From: Ivan Novikov Date: Thu, 31 Oct 2019 00:30:20 +0300 Subject: [PATCH] Kotlin examples for 08 chapter (#147) --- .../kotlin/01_set_covering.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 08_greedy_algorithms/kotlin/01_set_covering.kt diff --git a/08_greedy_algorithms/kotlin/01_set_covering.kt b/08_greedy_algorithms/kotlin/01_set_covering.kt new file mode 100644 index 0000000..5049fee --- /dev/null +++ b/08_greedy_algorithms/kotlin/01_set_covering.kt @@ -0,0 +1,26 @@ +var statesNeeded = setOf("mt", "wa", "or", "id", "nv", "ut", "ca", "az") +val stations = mapOf( + "kone" to setOf("id", "nv", "ut"), + "ktwo" to setOf("wa", "id", "mt"), + "kthree" to setOf("or", "nv", "ca"), + "kfour" to setOf("nv", "ut"), + "kfive" to setOf("ca", "az") +) + +fun main() { + val finalStations = mutableSetOf() + while (statesNeeded.isNotEmpty()) { + var bestStation: String? = null + var statesCovered = setOf() + stations.forEach { (station, states) -> + val covered = statesNeeded.intersect(states) + if (covered.size > statesCovered.size) { + bestStation = station + statesCovered = covered + } + } + statesNeeded = statesNeeded - statesCovered + bestStation?.let { finalStations.add(it) } + } + println(finalStations) +} \ No newline at end of file