Reputation: 4510
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
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