Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating differences of subsequent elements of a sequence in scala

Tags:

scala

I would like to do almost exactly this in scala. Is there an elegant way?

Specifically, I just want the difference of adjacent elements in a sequence. For example

input = 1,2,6,9
output = 1,4,3
like image 911
default.kramer Avatar asked Jun 28 '13 19:06

default.kramer


People also ask

How do you find the difference between all elements in an array?

Solution StepsDeclare an extra memory diff[n-1] of size n-1 to store differences of adjacent elements from index 0 to n-1. We run a loop from 0 to n - 2 to store differences in diff[n - 1]. Now we calculate and return the maximum subarray sum of diff[] array. We can find this value in O(n) time and O(1) space.

What is seq () in Scala?

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

How do you find the difference between two arrays in Scala?

In Scala Stack class , the diff() method is used to find the difference between the two stacks.

What does ::: mean in Scala?

:: - adds an element at the beginning of a list and returns a list with the added element. ::: - concatenates two lists and returns the concatenated list.


2 Answers

How about this?

scala> List(1, 2, 6, 9).sliding(2).map { case Seq(x, y, _*) => y - x }.toList
res0: List[Int] = List(1, 4, 3)
like image 56
Jean-Philippe Pellet Avatar answered Sep 28 '22 15:09

Jean-Philippe Pellet


Here is one that uses recursion and works best on Lists

def differences(l:List[Int]) : List[Int] = l match {
  case a :: (rest @ b :: _) => (b - a) :: differences(rest)
  case _ => Nil
}

And here is one that should be pretty fast on Vector or Array:

def differences(a:IndexedSeq[Int]) : IndexedSeq[Int] = 
  a.indices.tail.map(i => a(i) - a(i-1))

Of course there is always this:

def differences(a:Seq[Int]) : Seq[Int] = 
  a.tail.zip(a).map { case (x,y) => x - y }

Note that only the recursive version handles empty lists without an exception.

like image 41
Rüdiger Klaehn Avatar answered Sep 28 '22 14:09

Rüdiger Klaehn