加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

数组 – 有效地遍历匹配布尔条件的数组?

发布时间:2020-12-16 18:39:39 所属栏目:安全 来源:网络整理
导读:这是 Scala针对不耐烦的另一个问题 Write a function lteqgt(values: Array[Int],v: Int) that returns a triple containing the counts of values less than v,equal to v,and greater than v. 我这样做的方式是 scala def lteqgt(values: Array[Int],v: In
这是 Scala针对不耐烦的另一个问题

Write a function lteqgt(values: Array[Int],v: Int) that returns a
triple containing the counts of values less than v,equal to v,and
greater than v.

我这样做的方式是

scala> def lteqgt(values: Array[Int],v: Int): (Int,Int,Int) = (values.count(_ < v),values.count(_ == v),values.count(_ > v))
lteqgt: (values: Array[Int],v: Int)(Int,Int)

scala> lteqgt(Array(0,1,2,2),1)
res47: (Int,Int) = (2,3,2)

问题?
我正在遍历数组3次以收集计数,有没有办法在第一次收集值?一种惯用的方式?

解决方法

这是使用foldLeft的完美案例.它将只遍历您的集合一次,而不创建另一个集合(如groupBy所做的那样),并且与更通用的聚合相比,它更简洁.

def lteqgt(values: Array[Int],Int) =
  values.foldLeft((0,0)) {
    case ((lt,eq,gt),el) =>
      if (el < v) (lt + 1,gt)
      else if (el == v) (lt,eq + 1,gt)
      else (lt,gt + 1)
  }

如果你想要实现最高效率,同时避免使用命令式方法,那么尾递归是最佳选择:

def lteqgt(values: Array[Int],Int) = {
  def rec(i:Int,lt:Int,eq:Int,gt:Int):(Int,Int) =
    if (i == values.length) (lt,gt)
    else if (values(i) < v) rec(i + 1,lt + 1,gt)
    else if (values(i) == v) rec(i + 1,lt,gt)
    else rec(i + 1,gt + 1)
  rec(0,0)
}

这避免了在每次迭代时构造元组和盒装Ints.整个事情在java中编译while循环(如果你感兴趣,则为here is the transpiled output).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读