Bazzoner
Bazzoner

Reputation: 59

Find the sum of a list in Scala

If I have a list of strings and I know the numeric vlaue of each string in the list how do i get the sum of the list?

Example:

I know:

a = 1
b = 2
c = 3
d = 4
e = 5

I am given the following list:

List("a","b","d") 

what the best way of calculating the sum 7?

Thanks

Upvotes: 2

Views: 3613

Answers (3)

Danny Mor
Danny Mor

Reputation: 1263

If you're 100% sure it's only letters

List("a","b","d").foldLeft(0)(_ + _.hashCode - 96)

if not, you can map it before

val letters = (1 to 26).map(x => Character.toString((x+96).toChar) -> x).toMap

and use @sheunis's answer:

val input = List("a","b","d")
input.map(letters.getOrElse(_, 0)).sum

Upvotes: 0

Emiliano Conde
Emiliano Conde

Reputation: 1

If you know that the values are the same as the element position, then you can avoid a map:

object test {
  val list = List("a", "b", "c", "d", "e")

  def sumThem = (for((letter, value) <- list.zipWithIndex) yield(value + 1)).sum
}

scala> test.sumThem
res2: Int = 15

Upvotes: 0

sheunis
sheunis

Reputation: 1544

val a = Map("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4, "e" -> 5)

val b = List("a", "b", "d")

b.map(a.getOrElse(_, 0)).sum

Upvotes: 7

Related Questions