How to sum two neighbours in a list in scala

scala sum list
scala reduce sum
scala fold
scala list
scala reduceleft
scala list insert
scala list collect
scala list partition

If you have one Integer list in Scala, and you want to iterate through it and sum every two neighbours with the same value and return this as a list, how would one do that ?

So for example:

List(4, 4, 2, 6) => List(8, 2, 6)

I'm completely new to Scala, but I can imagine that pattern match or map could be useful.

def sumSameNeighbours: List[Int] => List[Int] = {
  ls match {
    case l1::l2:ls => l1 == l2
  }
}

This is what I can think of.

EDIT: How would I have to change the code in order to iterate from right to left instead from left to right?

So that f.e. it would be:

List(2, 2, 2, 6, 4) => List(2, 4, 6, 4)

instead of

List(2, 2, 2, 6, 4) => List(4, 2, 6, 4)

This is pretty close to your suggestion and seems basically to work:

import scala.annotation.tailrec

def sumSameNeighbors( ls : List[Int] ) : List[Int] = {
  @tailrec
  def walk( unsummed : List[Int], reverseAccum : List[Int] ) : List[Int] = {
    unsummed match {
      case a :: b :: rest if a == b => walk( rest, a + b :: reverseAccum )
      case a :: rest                => walk( rest, a :: reverseAccum )
      case Nil                      => reverseAccum.reverse
    }
  }
  walk( ls, Nil )
}

How to sum two neighbours in a list in scala - scala - html, If you have one Integer list in Scala, and you want to iterate through it and sum every two neighbours with the same value and return this as a list, how would one  How to calculate the sum of a List in Java and Scala By alvin ~ Posted Tue, 08/04/2015 - 15:31 As a quick note about a difference between Java and Scala, I recently wrote this blog post about How to Sum the Elements of a List in Java (ArrayList, LinkedList, etc.) .

Note: Based on final OP's specifications clarification, this answer doesn't exactly fit the question requirements.

Here is a solution using List.grouped(2):

list.grouped(2).toList
  .flatMap {
    case List(a, b) if a == b => List(a + b)
    case l => l
  }

The idea is to group consecutive elements by pair. If the pair has the same elements, we return their sum to be flatMaped and otherwise both elements untouched.

List(4, 4, 2, 6) => List(8, 2, 6)
List(2, 4, 4, 2, 6) => List(2, 4, 4, 2, 6)
List(2) => List(2)
List(9, 4, 4, 4, 2, 6) => List(9, 4, 8, 2, 6)

How to walk through a Scala collection with 'reduce' and 'fold , reduceLeft starts by comparing the first two elements in the collection scala> val a = Array(12, 6, 15, 2, 20, 9) a: Array[Int] = Array(12, 6, 15, 2, 20, 9) The following example shows how to get the sum of all the elements in  Otherwise, if the list is not empty, the result of the function is the combination of (a) the value of its head element (1, in this case), and (b) the sum of the remaining elements in the list (2,3,4). A slight restatement of that second sentence is: “The sum of a list of integers is the sum of the head element, plus the sum of the tail elements."

Another way using foldRight, which I find a good default for this sort of traversing a collection while creating a new one:

list.foldRight(List.empty[Int]) {
  case (x, y :: tail) if x == y => (x + y) :: tail
  case (x, list) => x :: list
}

Output of List(2, 2, 2, 6, 4) is List(2, 4, 6, 4) as requested.

The main thing I wasn't clear on from your examples is what the output should be if summing creates new neighbours: should List(8, 4, 2, 2) turn into List(8, 4, 4) or List(16)? This produces the second.

Scala List sum() method with example, Method Definition: def sum(num: math.Numeric[B]): B. Return Type: It returns the sum of all the elements of the list. Example #1: filter_none. edit close. This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.15, “How to use Lists in Scala match expressions.”. Problem. You know that a Scala List data structure is a little different than other collection data structures.

Sum of array elements excluding the elements which lie between a , Given an array of N unique numbers. Also given two numbers a and b such that a will always be before b in the array. The task is to find the sum of the array  Those examples show how to create a series of lists. The initial list named p1 contains one string, then p2 contains two strings, and finally p3 contains three strings. Prepending elements like this is exactly how the Scala List class is intended to be used. While that approach looks cumbersome in a small example, it makes sense in larger, real-world code.

Top 10 Algorithms for Coding Interview, 15) Minimum Size Subarray Sum The implementation of a linked list is pretty simple in Java. Two popular applications of linked list are stack and queue. GraphNode[] n){ val = x; neighbors = n; } public String toString(){ return "value: "+​  Sum Lists function in Scala. Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

S-99: Ninety-Nine Scala Problems, Given two indices, I and K, the slice is the list containing the elements from and In most cases, if an even number is written as the sum of two prime numbers, T) { var adj: List[Edge] = Nil def neighbors: List[Node] = adj.map(edgeTarget(_,  Though using :: is very common, there are additional methods that let you prepend or append single elements to a List: scala> val x = List(1) x: List[Int] = List(1) scala> val y = 0 +: x y: List[Int] = List(0, 1) scala> val y = x :+ 2 y: List[Int] = List(1, 2) You can also merge lists to create a new list. See Recipe 11.5 for examples. Discussion

Comments
  • What would be the expected result for List(4, 4, 4, 2, 6)?
  • That would be List(8, 4, 2, 6)
  • What about List(2, 4, 4, 2, 6)? Is it unchanged, or does it produce List(2, 8, 2, 6)? A few more examples would be helpful.
  • Yes, that would be List(2, 8, 2, 6)
  • Thank you very much. Seems to work good. One further question: How would I have to change the code in order to iterate from right to left instead from left to right? So that f.e. it would be List(2, 2, 2, 6, 4) => List(2, 4, 6, 4)
  • the easy way would just be def sumSameNeighborsFromRight( ls : List[Int] ) = sumSameNeighbors( ls.reverse ).reverse.
  • This would break if the input just started with a single unique number. The question doesn't really mention that though but it might be a good assumption.
  • Yeah, break was the wrong word as only the op would know what List(9, 4, 4, 4, 2, 6) should return. Steve's result would be different that's all.
  • @XavierGuihot This solution is wrong, it does not produce the correct answers. See the comments on the question for the correct transformation for List(2, 4, 4, 2, 6).