Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract two consecutive element in a list in Scala?

Tags:

list

scala

I would like to subtract two consecutive element in a list with numbers in Scala.

For example : I have this list :

val sortedList = List(4,5,6)

I would like to have an output list like diffList =(1, 1) where 5-4 = 1 and 6-5 = 1.

I tried the following code:

var sortedList = List[Int]()
var diffList = List[Int]()

for (i <- 0 to (sortedList.length - 1) ;j <- i + 1 to sortedList.length - 1) 
{
    val diff = (sortedList(j) - sortedList(i))
    diffList = diffList :+ diff
}

I have the following result for diffList =(1, 2, 1) but I want diffList = (1,1).

It's because of the for loop. it does not iterate over the two variables (i and j) at once.

like image 788
Sandra Avatar asked Jan 30 '21 19:01

Sandra


People also ask

What is list in Scala?

Scala - Lists. Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat.

What is the difference between its arguments and list fill in Scala?

Its arguments are just like those of List.fill: the first argument list gives the dimensions of the list to create, and the second describes the elements of the list. The only difference is that instead of the elements being fixed, they are computed from a function. Try the following example program. Save the above program in Demo.scala.

How to fold lists in Scala?

In this tutorial, we’ll look at how to fold lists in Scala using a variety of approaches. The List class’s fold functions take the data in the list, an initial value, and a combining function. They then step through the elements in the list and apply the provided function to them.

How do you subtract a number from an array in Python?

Subtraction in the Array Given an integer k and an array arr [], the task is to repeat the following operation exactly k times: Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.


2 Answers

You do not mutability nor imperative programming to solve this problem, functional programming got you covered.

def consecutiveDifferences(data: List[Int]): List[Int] =
  if (data.isEmpty) List.empty
  else data.lazyZip(data.tail).map {
    case (x, y) => y - x
 }

As I always say, the Scaladoc is your friend.
(Also, as an advice, the best way to learn functional programming is to forbid yourself from mutability)

like image 133
Luis Miguel Mejía Suárez Avatar answered Nov 15 '22 10:11

Luis Miguel Mejía Suárez


You can use the sliding method, which according to the docs:

/** Groups elements in fixed size blocks by passing a "sliding window"
 *  over them (as opposed to partitioning them, as is done in `grouped`.)
 *
 *  An empty collection returns an empty iterator, and a non-empty
 *  collection containing fewer elements than the window size returns
 *  an iterator that will produce the original collection as its only
 *  element.
 *  @see [[scala.collection.Iterator]], method `sliding`
 *
 *  @param size the number of elements per group
 *  @return An iterator producing ${coll}s of size `size`, except for a
 *          non-empty collection with less than `size` elements, which
 *          returns an iterator that produces the source collection itself
 *          as its only element.
 *  @example `List().sliding(2) = empty iterator`
 *  @example `List(1).sliding(2) = Iterator(List(1))`
 *  @example `List(1, 2).sliding(2) = Iterator(List(1, 2))`
 *  @example `List(1, 2, 3).sliding(2) = Iterator(List(1, 2), List(2, 3))`
 */

Then, solving your query is pretty straight forward:

diffList = sortedList.sliding(2).collect {
  case Seq(a, b) =>
    b - a
}.toList

Which results in List(1,1)

Code run at Scastie.

like image 41
Tomer Shetah Avatar answered Nov 15 '22 10:11

Tomer Shetah