Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce new array where all positive comes first, then negative or zero but in same order

Tags:

arrays

scala

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

like image 362
daydreamer Avatar asked Dec 24 '22 15:12

daydreamer


1 Answers

Consider filter and filterNot as follows,

b.filter(_ > 0) ++ b.filterNot(_ > 0)
like image 140
elm Avatar answered Mar 02 '23 01:03

elm