gpt4 book ai didi

arrays - 生成新数组,其中所有正数首先出现,然后是负数或零,但顺序相同

转载 作者:行者123 更新时间:2023-12-04 22:44:49 25 4
gpt4 key购买 nike

这是来自 Scala for the Impatient 的问题, Arrays 一章说明为

Given an array of integers, produce a new array that contains all positive values of the original array, in their original order, followed by all values that are zero or negative, in their original order.



我的尝试是
scala> val b = Array(-1, 2,3,4, -10, 0, -12)
b: Array[Int] = Array(-1, 2, 3, 4, -10, 0, -12)

scala> val(positive, negative) = b partition(_ > 0)
positive: Array[Int] = Array(2, 3, 4)
negative: Array[Int] = Array(-1, -10, 0, -12)

scala> positive ++ negative
res11: Array[Int] = Array(2, 3, 4, -1, -10, 0, -12)

我可以在一行中做得更好吗?我不确定

最佳答案

考虑 filterfilterNot如下,

b.filter(_ > 0) ++ b.filterNot(_ > 0)

关于arrays - 生成新数组,其中所有正数首先出现,然后是负数或零,但顺序相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com