Reputation: 1191
I'm trying to implement a simple algorithm in Kotlin
which finds only unique numbers in an array.
I cannot figuring out how to convert the map
into the uniqueArray
with elements which values equals to 1.
val array: IntArray = intArrayOf(4, 7, 3, 3, 4, 5)
val map: HashMap<Int, Int> = HashMap()
for (x in array) map.merge(x, 1, {v, _ -> v + 1})
// convert the map into an IntArray
val uniqueArray: IntArray = ...
Upvotes: 0
Views: 427
Reputation: 200196
Here's a complete algorithm that doesn't involve counting instances:
val input = intArrayOf(4, 7, 3, 3, 4, 5)
val duplicates = emptySet<Int>().toMutableSet()
val result = emptySet<Int>().toMutableSet()
for (it in input) {
if (duplicates.contains(it)) {
continue
}
if (!result.add(it)) {
result.remove(it)
duplicates.add(it)
}
}
Upvotes: 1
Reputation: 3504
You can use filter
and destructure entry into key and value as below:
val uniqueArray: IntArray = map
.filter { (k, v) -> v == 1 }
.keys
.toIntArray()
Upvotes: 1