Created
October 4, 2018 19:42
-
-
Save wolfendale/e9e3c708261a04b1542b54eb345c31f2 to your computer and use it in GitHub Desktop.
Maximum Sublist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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