sc_ray - 7 months ago 41

Scala Question

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

Answer

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)
```