Skip to content

Instantly share code, notes, and snippets.

@wolfendale
Created October 4, 2018 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfendale/e9e3c708261a04b1542b54eb345c31f2 to your computer and use it in GitHub Desktop.
Save wolfendale/e9e3c708261a04b1542b54eb345c31f2 to your computer and use it in GitHub Desktop.
Maximum Sublist
import scala.util.Random
implicit class SubsetList[A](list: List[A]) {
def sublists: Stream[List[A]] = for {
length <- (0 to list.length).toStream
combination <- list combinations length
} yield combination
}
def maxSublistBounded(list: List[Int], boundary: Int): (List[Int], Int) = {
val sublists = list.sublists
(sublists zip sublists.map(_.sum))
.takeWhile(_._2 <= boundary)
.maxBy(_._2)
}
maxSublistBounded((1 to 100).toList, 200)
maxSublistBounded((1 to 10).map(_ => Random.nextInt(10)).toList, 50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment