This is problem from Scala for the Impatient, chapter of Arrays stated as
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.
My attempt is
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)
Can I do this better in one line? I am not sure
Consider filter
and filterNot
as follows,
b.filter(_ > 0) ++ b.filterNot(_ > 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With