Дмитрий Цывцын
02/03/2022, 2:30 AMAlex
02/03/2022, 1:05 PMДмитрий Цывцын
02/04/2022, 6:08 AM// Solution #1
fun deleteNth1(elements: IntArray, maxOccurrences: Int) : IntArray {
// LinkedHashMap preserves the entry iteration order.
val occurrencesMap = LinkedHashMap<Int, Int>()
elements.forEach { element ->
occurrencesMap[element] = (occurrencesMap[element] ?: 0) + 1
}
return occurrencesMap.map { entry ->
val occurrences = if (entry.value < maxOccurrences) entry.value else maxOccurrences
Array(occurrences) { entry.key }
}.toTypedArray().flatten().toIntArray()
}
// Solution #2
fun deleteNth2(elements: IntArray, maxOccurrences: Int) : IntArray {
return elements.groupBy { it }
.flatMap { group -> group.value.take(maxOccurrences) }
.toIntArray()
}
// Solution #3
fun deleteNth3(elements: IntArray, maxOccurrences: Int) : IntArray {
val occurrencesMap = LinkedHashMap<Int, Int>()
// array can be larger
val array = Array(elements.size) { 0 }
var index = 0
for (element in elements) {
val occurrences = occurrencesMap[element] ?: 0
val newOccurrences = occurrences + 1
if (newOccurrences <= maxOccurrences) {
array[index] = element
}
occurrencesMap[element] = newOccurrences
}
return array.toIntArray()
}
Alex
02/07/2022, 7:59 AM//This code works but it changes the order thus code wars does not acccept it
fun getMaxOccurrence2(elements:IntArray, maxOccurrences:Int):IntArray{
var holdResult= listOf<Int>()
val result=elements.asSequence().groupBy { it }.values
for (items in result){
if (items.count()< maxOccurance){
continue
}
holdResult=holdResult.plus(items.take(maxOccurrences))
}
return holdResult.toIntArray()
}
Дмитрий Цывцын
02/10/2022, 3:32 AMAlex
02/10/2022, 12:09 PM