Neo-coder
Neo-coder

Reputation: 7840

Subtract adjacent list elements

My scala list contains following elements :

val A = List(12,1,34,34,45,56,7)

now I want to subtract list as below :

  List((12-1),(1-34),(34-34),(34-45),(45-56),(56-7))

so final result will be :

val result = List(11,-33,0,-11,-11,49)

Upvotes: 1

Views: 1661

Answers (6)

itsbruce
itsbruce

Reputation: 4843

I'm not impressed by the performance of the zip/map solutions. This could be done with a simple iterator, overriding the next() method. But I prefer streams

def subNeighbours(xs: List[Int]): Stream[Int] = xs match {
  case x :: y :: rest => (x - y) #:: subNeighbours(y :: rest)
  case _ => Stream.Empty
}

(subNeighbours(A)).toList

Inputs and outputs:

  • List(12, 1, 34, 34, 45, 56, 7) => List(11, -33, 0, -11, -11, 49)
  • List(1, 3, 2, 9, 0, 5) => List(-2, 1, -7, 9, -5)
  • List(1) => List()
  • List() => List()

Stream solution only traverses the list once.

Upvotes: 0

Markus1189
Markus1189

Reputation: 2869

And let's don't forget zipped:

val A = List(12,1,34,34,45,56,7)
(A,A.drop(1)).zipped.map(_-_)

Upvotes: 3

Chris Martin
Chris Martin

Reputation: 30736

Just to throw one more option into the mix:

(A zip A.drop(1)).map({ case (a, b) => a - b })

This gives you a little bit more type safety than sliding because Tuple2 codifies the fact that the intermediate collection's elements are pairs.

Upvotes: 2

ntn
ntn

Reputation: 1177

You could do:

val list = List(12, 1, 34, 45)
list.sliding(2).map {
 case a :: b :: Nil => a - b
}.toList

It should return what you need.

Upvotes: 1

jarandaf
jarandaf

Reputation: 4427

I think you need sliding (groups elements in fixed size blocks by passing a "sliding window" over them):

A.sliding(2,1).toList.map(x => x(0) - x(1))

Upvotes: 5

Anthony Zovich
Anthony Zovich

Reputation: 1

Well, The thinking behind this would be:

for(int i=0; i<list.length-1; i++){
list[i]= list[i]-list[i+1];
}

Now just add in the small litter details like setting result to the final values and you are golden.

Upvotes: -2

Related Questions