2

For a given Array[Byte] such as

val in = Array(104, 101, 108, 108, 111, 10, 119, 111, 114, 108, 100, 10)

how to split it by value 10 so that

val out = in.arr_split(10)

would deliver

Array( Array(104, 101, 108, 108, 111), 
       Array(119, 111, 114, 108, 100))

Assume in general many occurrences of splitting elements, for instance many 10.

If possible, a parallel solution is desired.

Many Thanks.

1
  • Convert it to a string (it looks very like ascii values to me), and then use split to split it on new lines. Commented Apr 13, 2014 at 17:45

3 Answers 3

4

Something like this should work:

  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))
Sign up to request clarification or add additional context in comments.

Comments

2

scalaz-stream solution. Instead of Array I use Vector here.

  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)

Output:

Vector(Vector(104, 101, 108, 108, 111), Vector(119, 111, 114, 108, 100))

Comments

0

Pimped version

  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)
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.