Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active February 25, 2021 13:48
Show Gist options
  • Select an option

  • Save fancellu/9a6332c851af98a6c64cd5acba35ef76 to your computer and use it in GitHub Desktop.

Select an option

Save fancellu/9a6332c851af98a6c64cd5acba35ef76 to your computer and use it in GitHub Desktop.
tail-recursive check to see if sum of list greater or equals to max, better than simply summing every element on a long list
import Numeric.Implicits._
import Ordering.Implicits._
def sumGreaterThanOrEquals[T](xs: List[T], max: T)(implicit num: Numeric[T]): Boolean = {
@tailrec
def inner(xs: List[T], accum: T): Boolean = {
xs match {
case x :: tail => if (accum+x>= max) true else inner(tail, accum+x)
case Nil => false
}
}
inner(xs, num.zero)
}
// if you want another way to implement
def sumGreaterThanOrEquals2[T](xs: List[T], max: T)(implicit num: Numeric[T]): Boolean = {
!xs.iterator.scanLeft(num.zero)(_+_).dropWhile(_<max).isEmpty
}
println(sumGreaterThanOrEquals(List(1,2,3),99))
println(sumGreaterThanOrEquals(List(1,2,3),3))
println(sumGreaterThanOrEquals(List(1,2,3),0))
println(sumGreaterThanOrEquals(List(1,2.2,3.3),2.4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment