Can we improve on my code to swap adjacent array elements in Scala? -


i'm learning scala working exercises book "scala impatient". 1 exercise asks that:

write loop swaps adjacent elements of array of integers. example, array(1, 2, 3, 4, 5) becomes array(2, 1, 4, 3, 5)

i did in 3 different ways, 1 of follows.i'm curious if can improved per comments i've put inline.

def swapwithgrouped(a: array[int]) = {   a.grouped(2).map {     // todo: can use reverse here?     case array(x, y) => array(y, x)     // todo: can use identity function here?     case array(x) => array(x)   }.flatten.toarray } 

you use .flatmap instead of .map{..}.flatten.
don't need match single element array, use variable (although feel depends on problem, showing symmetry in patterns nice , makes intent more explicit).

so :

scala> def swapwithgrouped(a: array[int]) = {          a.grouped(2).flatmap {            case array(x, y) => array(y, x)            case single => single          }.toarray        } swapwithgrouped: (a: array[int])array[int]  scala> swapwithgrouped(a)  // array(1,2,3,4,5) res0: array[int] = array(2, 1, 4, 3, 5) 

the array(x,y) => array(y,x) pretty easy read wrong, .reverse makes intention more explicit , has added benefit can remove single-element case.

scala> def swapwithgrouped(a: array[int]) = a.grouped(2).flatmap(_.reverse).toarray swapwithgrouped: (a: array[int])array[int] 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -