Scala数组的间隔数的索引(Scala the index of a number in which interval of an array)
假设我有一个(0, 0.1, 0.2, ..., 1)的数组,我有一个数字0.15 ,我希望得到它的索引。 由于0.15 > 0.1和0.15 < 0.2 ,因此它在区间2 。 有没有最先进的方法来做到这一点? 目前我使用带有var变量的for循环并遍历每个间隔,但我不认为这是最好的方法。
Suppose I have an array of (0, 0.1, 0.2, ..., 1) and I have a number 0.15, I'd hope to get the index of that. Since 0.15 > 0.1 and 0.15 < 0.2, it is in the interval 2. Is there a state-of-art way to do that? Currently I use a for loop with a var variable and go through each interval but I do not think it's the best way.
最满意答案
假设数组已订购,您可以尝试:
arr.indexWhere(_ >= 0.15) - 1如果没有这样的实例,你会得到 - 2。
assuming the array is ordered you can try:
arr.indexWhere(_ >= 0.15) - 1if there is no such instance you get - 2.
更多推荐
发布评论