Last active
December 21, 2015 00:39
-
-
Save tmoerman/6222269 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package be.webcomrades.spike.partition | |
object Algo { | |
def partition(list: List[Int], acceptedSizes: Set[Int]) : List[List[Int]] = { | |
def internal(list: List[Int], result: List[List[Int]]) : List[List[Int]] = list match { | |
case Nil => result | |
case i :: rest => | |
result match { | |
case Nil => internal(rest, List(List(i))) | |
case l :: lists => | |
if (acceptedSizes.contains(l.sum)) { | |
internal(rest, List(i) :: l :: lists) | |
} else if (i + l.sum <= acceptedSizes.max) { | |
internal(rest, (l :+ i) :: lists) | |
} else { | |
internal(rest, List(i) :: l :: lists) | |
} | |
} | |
} | |
internal(list, Nil).reverse | |
} | |
def icon(i: Int) = i match { | |
case 2 => "()" | |
case 3 => "[ ]" | |
case 6 => "< >" | |
} | |
def row(l: List[Int]) = l.map(icon).mkString | |
def draw(l: List[List[Int]]): Unit = l.map(row).map(println) | |
/* | |
val range = (6 to 8).toSet | |
val input = List(6, 2, 6, 2, 2, 2, 3, 3, 2, 6, 3, 3, 2, 2, 2) | |
< >()< >()()()[ ][ ]()< >[ ][ ]()()() | |
draw(partition(input, range)) | |
< > | |
()< > | |
()()() | |
[ ][ ] | |
()< > | |
[ ][ ] | |
()()() | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment