Khoa
Khoa

Reputation: 185

Functional version of a typical nested while loop

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 
  }

Upvotes: 0

Views: 286

Answers (1)

jwvh
jwvh

Reputation: 51271

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

Upvotes: 3

Related Questions