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

数组 – 将Scala Array转换为唯一排序列表的高效方法

发布时间:2020-12-16 19:02:32 所属栏目:安全 来源:网络整理
导读:任何人都可以在 Scala中优化以下声明: // maybe largeval someArray = Array(9,1,6,2,9,4,5,6) // output a sorted list which contains unique element from the array without 0val newList=(someArray filter (_0)).toList.distinct.sort((e1,e2) = (e1
任何人都可以在 Scala中优化以下声明:

// maybe large
val someArray = Array(9,1,6,2,9,4,5,6) 

// output a sorted list which contains unique element from the array without 0
val newList=(someArray filter (_>0)).toList.distinct.sort((e1,e2) => (e1 > e2))

由于性能至关重要,有没有更好的方法?

谢谢.

解决方法

到目前为止,这条简单的代码是最快的代码之一:

someArray.toList.filter (_ > 0).sortWith (_ > _).distinct

但到目前为止,明显的赢家是 – 由于我的测量 – 杰维斯·史密斯.也许如果Rex的代码是固定的,它看起来不一样.

典型免责声明1 2:

>我修改了代码来接受一个Array并返回一个List.
>典型基准考虑因素:

>这是随机数据,平均分配.对于100万个元素,我创建了一个1百万的数组,范围在0到100万之间.因此,或多或少的零,或多或少的重复,它可能会有所不同.
>它可能依赖于机器等.我使用单核CPU,Intel-Linux-32bit,jdk-1.6,scala 2.9.0.1

下面是生成图形(gnuplot)的底层benchcoat-code and the concrete code . Y轴:以秒为单位的时间. X轴:阵列中的100 000到1 000 000个元素.

更新:

在找到Rex代码的问题之后,他的代码与Jed的代码一样快,但最后一个操作是将其Array转换为List(以完全填充我的基准界面).使用var result = List [Int]和result = someArray(i)::结果加快了他的代码,所以它的速度是Jed-Code的两倍.

另一个可能有趣的发现是:如果我按照filter / sort / distinct(fsd)=>的顺序重新排列我的代码. (dsf,dfs,fsd,…),所有6种可能性没有显着差异.

(编辑:李大同)

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

    推荐文章
      热点阅读