对于给定的Array[Byte]
,例如
val in = Array(104, 101, 108, 108, 111, 10, 119, 111, 114, 108, 100, 10)
如何按价值10
拆分
val out = in.arr_split(10)
将提供
Array( Array(104, 101, 108, 108, 111),
Array(119, 111, 114, 108, 100))
通常假设出现了很多分裂元素,例如很多10
。
如果可能,需要并行解决方案。
非常感谢。
答案 0 :(得分:4)
这样的事情应该有效:
def split(l: Array[Int], i:Int):Array[Array[Int]] = {
l match {
case Array() => Array()
case _ =>
val (h, t) = l.span(a => a != i)
Array(h) ++ split(t.drop(1), i)
}
}
val in = Array(104, 101, 108, 108, 111, 10, 119, 111, 114, 108, 100, 10)
val out = split(in, 10)
// res: Array[Array[Int]] = Array(Array(104, 101, 108, 108, 111), Array(119, 111, 114, 108, 100))
答案 1 :(得分:2)
scalaz-stream解决方案。我在这里使用Vector而不是数组。
val in = Vector(104, 101, 108, 108, 111, 10, 119, 111, 114, 108, 100, 10)
val P = scalaz.stream.Process
implicit val eq = scalaz.Equal.equal[Int]((l, r) => l == r)
println(P.emitSeq[Task, Int](in).splitOn(10).filter(!_.isEmpty).runLog.run)
输出:
Vector(Vector(104, 101, 108, 108, 111), Vector(119, 111, 114, 108, 100))
答案 2 :(得分:0)
Pimped版
implicit def toDivide[A, B <% TraversableLike[A, B]](a : B) = new {
private def divide(x : B, condition: (A) => Boolean) : Iterable[B] = {
if (x.size > 0)
x.span(condition) match {
case (e, f) => if (e.size > 0) Iterable(e) ++ divide(f.drop(1),condition) else Iterable(f)
}
else
Iterable()
}
def divide(condition: (A) => Boolean): Iterable[B] = divide(a, condition)
}