0

I hope this question may please functional programming lovers. Could I ask for a way to translate the following fragment of code to a pure functional implementation in Scala with good balance between readability and execution speed?

Description: for each elements in a sequence, produce a sub-sequence contains the elements that comes after the current elements (including itself) with a distance smaller than a given threshold. Once the threshold is crossed, it is not necessary to process the remaining elements

  def getGroupsOfElements(input : Seq[Element]) : Seq[Seq[Element]] = {
    val maxDistance = 10 // put any number you may
    var outerSequence = Seq.empty[Seq[Element]]

    for (index <- 0 until input.length) {
      var anotherIndex = index + 1
      var distance = input(index) - input(anotherIndex) // let assume a separate function for computing the distance
      var innerSequence = Seq(input(index))

      while (distance < maxDistance && anotherIndex < (input.length - 1)) {
        innerSequence = innerSequence ++ Seq(input(anotherIndex))
        anotherIndex = anotherIndex + 1
        distance = input(index) - input(anotherIndex)
      }

      outerSequence = outerSequence ++ Seq(innerSequence)
    }

    outerSequence 
  }
3
  • 1
    "Best" is pretty subjective. By what standard? Readability? Speed? Memory usage? Commented Feb 16, 2017 at 22:36
  • thanks, good point! Commented Feb 16, 2017 at 22:39
  • 2
    The code above will throw an ArrayIndexOutOfBoundsException when index is input.length-1. Commented Feb 16, 2017 at 22:51

1 Answer 1

3

You know, this would be a ton easier if you added a description of what you're trying to accomplish along with the code.

Anyway, here's something that might get close to what you want.

def getGroupsOfElements(input: Seq[Element]): Seq[Seq[Element]] =
  input.tails.map(x => x.takeWhile(y => distance(x.head,y) < maxDistance)).toSeq
Sign up to request clarification or add additional context in comments.

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.