Scala中合并两个相邻indicies的有效方法 [英] Efficient method of merging two neighboring indicies in Scala
问题描述
什么是Scala中合并两个相邻indicies的最有效的方法?我心里有一个讨厌的while循环与复制。
What would be a most efficient method of merging two neighboring indicies in Scala? What I have in mind a nasty while loops with copying.
例如,有一个缓冲区数组A,长度为N的新数组需要被生成,使得对 A(I)= A(I)+ A(I + 1)
,其中 I< ñ
For example, there's a buffer array A, with length N. The new array need be generated such that for A(i) = A(i) + A(i+1)
, where i < N
例如,合并,总结了第二和第三个元素,并产生一个新的数组。 ArrayBuffer(1,2,4,3)=&GT; ArrayBuffer(1,6,3)
For example, merging and summing the second and third element, and generate a new array.
ArrayBuffer(1,2,4,3) => ArrayBuffer(1,6,3)
更新:
我想,我拿出一些解决方案,但不喜欢它了。改善任何建议将是非常美联社preciated。
UPDATE: I think I come up with some solution, but doesn't like it much. Any suggestion to improve would be highly appreciated.
斯卡拉&GT; VAL I = 1
我:INT = 1
斯卡拉&GT; ArrayBuffer(1,2,4,3).zipWithIndex.foldLeft(ArrayBuffer [INT]())((K,V)=&GT;如果(v._2 == I + 1){K(k.length-1 )=(k.last + v._1); K;}其他K + = v._1)
推荐答案
得到邻居的最简单的方法是使用滑动
方法。
The simplest way to get neighbors is to use sliding
method.
a.sliding(2, 1).map(_.sum)
其中第一个参数是一个大小,第二个是一步。
where the first argument is a size and the second one is step.
如果你想保持第一和最后一个元素完好这样的事情应该工作:
If you want to keep the first and the last element intact something like this should work:
a.head +: a.drop(1).dropRight(1).sliding(2, 1).map(_.sum).toArray :+ a.last
如果你想避免在附加/ prePEND复制和阵列可以如下重写:
If you want to avoid copying and array on append/prepend you can rewrite it as follows:
val aa = a.sliding(2, 1).map(_.sum).toArray
aa(0) = a.head
aa(aa.size - 1) = a
或使用 ListBuffer 这提供恒定的时间prePEND和追加。
or use ListBuffer which provides constant time prepend and append.
应该还可以使用迭代器
:
val middle: Iterator[Int] = a.drop(1).dropRight(1).sliding(2, 1).map(_.sum)
(Iterator(a.head) ++ middle ++ Iterator(a.last)).toArray // or toBuffer
这篇关于Scala中合并两个相邻indicies的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!