Friday 13 January 2012

In response to 'Generating every combination without duplicates'

Peter, a friend of mine, posted this : Java riddle... Here is my scala solution using Scalaz:
import scalaz._
import Scalaz._

object Combi1 {
  def combine[A](xs: List[A]): List[List[A]] = xs.replicate[List](xs.size).sequence
  
  def main(args: Array[String]): Unit = {
    val list = List(1, 1, 2, 3, 3, 3)
    def isCorrect(list: List[Int]) : Boolean = {
      list.count(i => i == 1) == 2 &&
      list.count(i => i == 2) == 1 &&
      list.count(i => i == 3) == 3
    }
    val combi = combine(list).filter(l => isCorrect(l)).distinct
    println(combi.size + " elements")
    combi.foreach(l => println(l))
  } 
}

1 comment:

Peter Lawrey said...

That is a much shorter solution. The main trick I was looking for was to only consider valid solutions instead of filtering all possible combinations e.g. if the possible combinations is much, much higher than the number of valid ones.

I suspect this too is simpler in Scala, but I wouldn't know where to start. ;)

Blog Archive