reduce list of integers/range of integers in scala
Asked Answered
C

4

6

Total newbie question here...Today while trying to calculate sum of a list of integers(actually BitSet), I ran into overflow scenarios and noticed that the return type of(sum/product) is Int. Are there any methods in Range/List to sum up or say multiply all values to Long?

val x = 1 to Integer.MaxValue
println(x.sum) //prints -1453759936

thanks

Camilacamile answered 26/8, 2011 at 6:17 Comment(0)
C
12

Convert the elements to Long (or BigInt should that go that far) while summing:

x.view.map(_.toLong).sum

You can also go back to fold

x.foldLeft(0L)(_ + _)

(Note: should you sum over a range, maybe it would be better do a little math, but I understand that is not what you did in fact)

Correy answered 26/8, 2011 at 6:32 Comment(0)
S
3

Compare:

>> val x = 1 to Int.MaxValue
x: scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne = Range(...)

With:

>> val x = 1L to Int.MaxValue
x: scala.collection.immutable.NumericRange.Inclusive[Long] = NumericRange(...)

Note that the first uses Int.to, and the latter used Long.to (where Int.MaxValue is up-converted automatically). Of course, the sum of a consecutive integer sequence has a very nice discrete formula :)

Happy coding.

Sicken answered 26/8, 2011 at 6:31 Comment(2)
Have a look at issues.scala-lang.org/browse/SI-4658 for the yet-to-come improvement. :-)Ruthful
@Ruthful Very nice that it's making it std :)Sicken
Z
2

This isn't very efficient, but the easiest way:

val x = 1L to Int.MaxValue
println(x.sum) //prints 2305843008139952128

If you need x to contain Ints rather than Longs, you can do

val x = 1 to Int.MaxValue
println(x.foldLeft(0L)(_+_))
Zinciferous answered 26/8, 2011 at 6:31 Comment(0)
K
1
Range.Long(1, Int.MaxValue, 1).sum
Krenek answered 26/8, 2011 at 6:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.