I'm looking for an most efficient way in Kotlin/Java to filter a List
down by a certain percentage and with the removal of filtered elements will be applied across the collection in a uniformed fashion (i.e. - the elements to be removed span across the entire collection evenly);
For Example
- filter the following by 50%
[0,1,2,3,4,5,6,7,8,9] = [0,2,4,6,8]
- filter the following by 10%
[1,100,1000,10000] = [1,100,10000]
I came up with the following Kotlin extension function & it works great when the percentage < 50% and the collection is large but when the collection >50% then this approach falls over as it only handles integer division.
private fun <E> List<E>.filterDownBy(perc: Int): List<E> {
val distro = this.size / ((perc * this.size) / 100)
if (perc == 0 || distro >= this.size)
return this
return this.filterIndexed { index, _ -> (index % distro) != 0 }
Is there a better way to do this & will also work when the percentage is >50%?