elm
elm

Reputation: 20415

Scala 2D array operations on rows from the second item

Given a 2D array, for instance

val in = Array( Array(10,11,12),
                Array(20,21,22))

would like to multiply by 10 each element in each row from the second element on, the first element in each row remains unmodified; the desired outcome in the example would be

val out = Array( Array(10,110,120),
                 Array(20,210,220))

Many Thanks.

Upvotes: 1

Views: 695

Answers (3)

Iurii Perevertailo
Iurii Perevertailo

Reputation: 2707

1) This code can throw Exception: java.util.NoSuchElementException: next on empty iterator if one of arrays will empty

in.map(a => {a.head +: a.tail.map(_*10) })

2) more preferable on my mind, but if your array happens to have elements equal to the first one, they won't be multiplied (comment by Alexey Romanov)

in.map(a => a.map(t => if (a.indexOf(t)==0) t else t*10))

3) safe variant of 1)

in.map(a => a.take(1) ++ a.slice(1, a.length).map(_*10))

Upvotes: 1

Ashalynd
Ashalynd

Reputation: 12563

val out = in.map(_.zipWithIndex.map {m => 
    { if (m._2==0) m._1 else m._1*10 }
} )

or if you don't like generating the indexes:

val out = in.map (m => (
    for {
        h <- m.headOption
    } yield h +:  m.tail.map(_ * 10)
) getOrElse Array())

(both approaches are safe if one of the arrays is empty)

Upvotes: 2

serejja
serejja

Reputation: 23851

Edited:

val out = in.map {
  case Array(head, tail @ _*) => head +: tail.toArray.map(_ * 10)
  case _ => ...
}

A simplier but a bit unsafe solution:

val out = in.map(arr => arr.head +: arr.tail.map(_ * 10))

Upvotes: 3

Related Questions