sc_ray sc_ray - 1 year ago 75
Scala Question

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?


dhg dhg
Answer Source

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

    case Array(x,y) => Array(y,x)
    case Array(x) => Array(x)
  }.toArray // Array(2, 1, 4, 3, 5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download