Kotlin examples for 08 chapter (#147)
This commit is contained in:
committed by
Aditya Bhargava
parent
591111e596
commit
009689b294
26
08_greedy_algorithms/kotlin/01_set_covering.kt
Normal file
26
08_greedy_algorithms/kotlin/01_set_covering.kt
Normal file
@@ -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<String>()
|
||||||
|
while (statesNeeded.isNotEmpty()) {
|
||||||
|
var bestStation: String? = null
|
||||||
|
var statesCovered = setOf<String>()
|
||||||
|
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)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user