Nat Strangerweather
03/17/2022, 7:39 PMletterList.value
all the "A"s in boardLetterList
are removed. Is there a way of getting only one "A" filtered out if I only have one in my letterList?
val difference = boardLetterList.filterNot{ letterList.value!!.contains(it) }
Youssef Shoaib [MOD]
03/17/2022, 7:51 PMMutableCollection.remove()
specifies:
Removes a single instance of the specified element from this collection, if it is present.and so:
val difference = buildList(boardLetterList.size) {
addAll(boardLetterList)
for (letter in letterList.value!!){
remove(letter)
}
}
Nat Strangerweather
03/17/2022, 7:53 PMephemient
03/17/2022, 9:29 PMephemient
03/17/2022, 9:34 PMfun <T> Iterable<T>.removeAllOnce(elements: Iterable<T>): List<T> {
val removeCounts = elements.groupingBy { it }.eachCountTo(mutableMapOf())
return this.filter { element ->
val count = removeCounts[element] ?: return@filter true
if (count > 0) {
removeCounts[element] = count - 1
false
} else true
}
}
Youssef Shoaib [MOD]
03/18/2022, 9:09 AMremove
has to iterate over the whole list to find the element to remove. So yes, OP, the removeAllOnce solution with the multiset is significantly faster!ephemient
03/19/2022, 1:48 AMIterable.removeAll
does something similar but without counting