我在Kotlin/Java中寻找一种最有效的方法,以一定的百分比过滤List,并且随着过滤元素的删除,将以统一的方式在集合中应用(即,要在整个集合中平均删除的元素);
例如
[0,1,2,3,4,5,6,7,8,9] = [0,2,4,6,8]过滤以下内容[1,100,1000,10000] = [1,100,10000]过滤以下内容我提出了下面的Kotlin扩展函数&当百分比< 50%且集合很大时,它工作得很好,但是当集合>50%时,这种方法就结束了,因为它只处理整数除法。
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%时也能工作吗?
发布于 2019-06-03 09:51:17
我不认为标准库中有太多有用的东西,但我想出了一种“手动”方法:
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 (取每个元素)之间的任何比例。
(可能有一种只使用整数运算的方法,但使用浮点可能更容易编码和理解。)
(通过使用filter(),您可能会使它看起来更有功能,但这并不合适,因为lambda必须使用和更新外部状态。)
https://stackoverflow.com/questions/56417097
复制相似问题