Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping array values with for and yield scala

I am trying to swap every pair of values in my array using for and yield and so far I am very unsuccessful. What I have tried is as follows:

val a = Array(1,2,3,4,5) //What I want is Array(2,1,4,3,5)

for(i<-0 until (a.length-1,2),r<- Array(i+1,i)) yield r

The above given snippet returns the vector 2,1,4,3(and the 5 is omitted)

Can somebody point out what I am doing wrong here and how to get the correct reversal using for and yields?

Thanks

like image 892
sc_ray Avatar asked Apr 14 '12 23:04

sc_ray


4 Answers

a.grouped(2).flatMap(_.reverse).toArray

or if you need for/yield (much less concise in this case, and in fact expands to the same code):

(for {b <- a.grouped(2); c <- b.reverse} yield c).toArray
like image 147
Rogach Avatar answered Sep 19 '22 10:09

Rogach


It would be easier if you didin't use for/yield:

a.grouped(2)
  .flatMap{ 
    case Array(x,y) => Array(y,x)
    case Array(x) => Array(x)
  }.toArray // Array(2, 1, 4, 3, 5)
like image 27
dhg Avatar answered Sep 21 '22 10:09

dhg


I don't know if the OP is reading Scala for the Impatient, but this was exercise 3.3 .

I like the map solution, but we're not on that chapter yet, so this is my ugly implementation using the required for/yield. You can probably move some yield logic into a guard/definition.

for( i <- 0 until(a.length,2); j <- (i+1).to(i,-1) if(j<a.length) ) yield a(j)

I'm a Java guy, so I've no confirmation of this assertion, but I'm curious what the overhead of the maps/grouping and iterators are. I suspect it all compiles down to the same Java byte code.

like image 23
Joseph Lust Avatar answered Sep 20 '22 10:09

Joseph Lust


Another simple, for-yield solution:

def swapAdjacent(array: ArrayBuffer[Int]) = {
    for (i <- 0 until array.length) yield (
        if (i % 2 == 0)
            if (i == array.length - 1) array(i) else array(i + 1)
        else array(i - 1)
    )
}
like image 26
Haris Osmanagić Avatar answered Sep 20 '22 10:09

Haris Osmanagić