Scala: Find max sum of consecutive negative numbers in a List of Double -


i have list[double] following values:

{-1.2200000000000006, -1.3200000000000003, -1.0099999999999998, 22.22, 11.11,  -31.310000000000002, -0.9799999999999986,-4, -5, 3, 2, 2.959999999999999}` 

i find max sum of consecutive negative numbers.

so original list separate consecutive lists of negative , positive

{    {-1.2200000000000006, -1.3200000000000003, -1.0099999999999998},   {22.22, 11.11},   {-31.310000000000002, -0.9799999999999986,-4, -5},   {3, 2, 2.959999999999999} } 

then remove positive consecutive numbers

{    {-1.2200000000000006, -1.3200000000000003, -1.0099999999999998},   {-31.310000000000002, -0.9799999999999986,-4, -5} } 

then sum

{-3.5500000000000007, -41.29} 

then change absolute values

{3.5500000000000007, 41.29} 

then find max = 41.29

if really mean sum consecutive negative numbers, , find maximum sum, it.

val nums = list(-1.2200000000000006, -1.3200000000000003, -1.0099999999999998,         22.22, 11.11, -31.310000000000002, -0.9799999999999986, 2.959999999999999)  nums.foldleft(list[double]()){   case (l,n) if n < 0 => if (l.isempty) list(n) else n + l.head :: l.tail   case (l, _) => double.minvalue :: l }.max // res0: double = -3.5500000000000007 

update

ok, minor change you're after.

nums.foldleft(list(0.0)){   case (l,n) if n < 0 => n + l.head :: l.tail   case (l, _) => 0.0 :: l }.min.abs // res0: double = 32.29 

note: you're after minimum sum. if want expressed positive number can absolute value after fact.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -