Listing combinations WITH repetitions in Scala

后端 未结 7 835
盖世英雄少女心
盖世英雄少女心 2021-01-12 01:18

Trying to learn a bit of Scala and ran into this problem. I found a solution for all combinations without repetions here and I somewhat understand the idea behind i

7条回答
  •  失恋的感觉
    2021-01-12 01:29

    Daniel -- I'm not sure what Alex meant by duplicates, it may be that the following provides a more appropriate answer:

    def perm[T](n: Int, l: List[T]): List[List[T]] =
      n match {
        case 0 => List(List())
        case _ => for(el <- l.removeDuplicates;
                    sl <- perm(n-1, l.slice(0, l.findIndexOf {_ == el}) ++ l.slice(1 + l.findIndexOf {_ == el}, l.size)))
                yield el :: sl
    }
    

    Run as

    perm(2, List(1,2,2,2,1)) 
    

    this gives:

    List(List(2, 2), List(2, 1), List(1, 2), List(1, 1))
    

    as opposed to:

    List(
      List(1, 2), List(1, 2), List(1, 2), List(2, 1), 
      List(2, 1), List(2, 1), List(2, 1), List(2, 1), 
      List(2, 1), List(1, 2), List(1, 2), List(1, 2)
    )
    

    The nastiness inside the nested perm call is removing a single 'el' from the list, I imagine there's a nicer way to do that but I can't think of one.

提交回复
热议问题