按一定百分比均匀过滤列表-Kotlin/Java [英] Evenly filter a list down by a certain percentage - Kotlin/Java
问题描述
我正在寻找Kotlin/Java中最有效的方法,以按一定百分比向下过滤List
,并且删除过滤后的元素将以统一的方式应用于整个集合(即-均匀地移到整个集合中)
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);
例如
- 将以下内容过滤50%
[0,1,2,3,4,5,6,7,8,9] = [0,2,4,6,8]
- 将以下内容过滤10%
[1,100,1000,10000] = [1,100,10000]
- 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]
我想出了以下Kotlin扩展功能&当百分比< 50%且集合很大,但是当集合> 50%时,此方法将失败,因为它仅处理整数除法.
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 }
是否有更好的方法来做到这一点?百分比> 50%时也会起作用吗?
Is there a better way to do this & will also work when the percentage is >50%?
推荐答案
我认为标准库中没有什么可以帮助您的,但是我想出了这种手动"方法:
I don't think there's much in the standard library that will help, but I've come up with this ‘manual’ approach:
fun <T> List<T>.takeProportion(prop: Double): List<T> {
if (prop < 0 || prop > 1)
throw IllegalArgumentException("prop ($prop) must be between 0 and 1")
val result = ArrayList<T>()
var tally = 0.5
for (i in this) {
tally += prop
if (tally >= 1.0) {
result += i
tally -= 1
}
}
return result
}
它使用一种错误扩散方式来确保值在列表中均匀地使用,并使用浮点数,以便它可以平滑地处理从0.0(给出一个空列表)到1.0(获取每个元素).
It uses a sort of error-diffusion way to ensure that the values are taken evenly across the list, and uses floating-point so that it copes smoothly with any proportion from 0.0 (giving an empty list) to 1.0 (taking every element).
(也许有一种方法可以只使用整数算术,但是使用浮点数可能更易于编码和理解.)
(There's probably a way of doing it using only integer arithmetic, but using floating-point is probably simpler to code and understand.)
(您可以使用filter()
使其外观更具功能性,但这并不恰当,因为lambda必须使用并更新外部状态.)
(You could probably make it more functional-looking by using filter()
, but that's not really appropriate because the lambda would have to use, and update, external state.)
这篇关于按一定百分比均匀过滤列表-Kotlin/Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!