Code to enumerate permutations in Scala

后端 未结 11 2053
臣服心动
臣服心动 2020-12-02 16:06

I coded a function to enumerate all permutations of a given list. What do you think of the code below?

def interleave(x:Int, l:List[Int]):List[List[Int]] = {         


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 16:39

    def permutator[T](list: List[T]): List[List[T]] = {
    
      def _p(total: Int, list: List[T]): List[List[T]] = {
        if (total == 0) {
          // End of the recursion tree
          list.map(List(_))
        } else {
          // Controlled combinatorial 
          // explosion while total > 0          
          for (i <- list;
               j <- _p(total - 1, list)) 
            yield { i :: j }
    
          // It is a recursion tree to generate the 
          // permutations of the elements
          // --------------------------------------
          // total = 0 => _p returns 3 elements (A, B, C) 
          // total = 1 => _p returns 3 * 3 List(List(A, A)...
          // total = 2 => _p returns 3 * 3 * 3 elements List(List(A, A, A)...
    
        }
      }
    
      _p(list.length - 1, list)
    }
    
    permutator(List("A", "B", "C"))
    
    // output:
    List(A, A, A),List(A, A, B),List(A, A, C),List(A, B, A),List(A, B, B),
    List(A, B, C),List(A, C, A),List(A, C, B),List(A, C, C),List(B, A, A),
    List(B, A, B),List(B, A, C),List(B, B, A),List(B, B, B),List(B, B, C),
    List(B, C, A),List(B, C, B),List(B, C, C),List(C, A, A),List(C, A, B),
    List(C, A, C),List(C, B, A),List(C, B, B),List(C, B, C),List(C, C, A),
    List(C, C, B),List(C, C, C)
    

提交回复
热议问题