2016-05-16 61 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 }