GameOfThrows
GameOfThrows

Reputation: 4510

Scala how to repeat the first element of Array until Array.size reach a certain number

I have a Array of length 3 say Array(3,4,5) and I have a target length which is an Int say 7. How do I pad the Array with it's first element until the length of the Array reaches the Int?

val A = Array(3,4,5)
val T = 7
//Desired output Array(3,3,3,3,3,4,5)

My current method:

val difflength = T - A.size
val firstElement = A.head
val PadArray = (for(i <- 0 to difflength) yield firstElement).toArray
PadArray ++ A

Is there an easier way to do this?

Upvotes: 2

Views: 325

Answers (1)

jub0bs
jub0bs

Reputation: 66234

Array's fill method comes in handy for this:

val a = Array(3,4,5)
val b = {
  val t = 7
  val diffLength = t - a.size
  val firstElement = a.head
  Array.fill(diffLength)(firstElement) ++ a
}

Result:

scala> b
res0: Array[Int] = Array(3, 3, 3, 3, 3, 4, 5)

Upvotes: 3

Related Questions