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
是可以接受的。