2016-05-16 103 views
0

給定具有奇數個元素的矢量v,它以0開頭和結尾,我想用它的中心向兩個方向掃描時找到的第一個非正元素填充它,如由此代碼片段執行:在Scala中填充矢量的兩端

val v  = Vector(0, 3, -1, 4, 1, 4, 0) 
val center = v.length/2 
val end0 = v.lastIndexWhere(_ <= 0, center) 
val end1 = v.indexWhere (_ <= 0, center) 

println(Vector.fill(end0)(v(end0)) ++ v.slice(end0, end1) ++ Vector.fill(v.length-end1)(v(end1))) 

其中產生Vector(-1, -1, -1, 4, 1, 4, 0)。有更簡潔的方法來做到這一點嗎?使用可變集合來表示v是可以接受的。

回答

1

不是真的更簡潔,但你可以使用zipWithIndexmap - 只是另一種變體:

val (end0, end1) = (v.lastIndexWhere(_ <= 0, center), v.indexWhere(_ <= 0, center)) 
val (end0_val, end1_val) = (v(end0), v(end1)) 
v.zipWithIndex map { case (value, ind) => if (ind < end0) end0_val else if (ind < end1) value else end1_val }