Code to enumerate permutations in Scala

后端 未结 11 2076
臣服心动
臣服心动 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 16:46

    I guess you are practicing your Scala programming skill. Here is another one, where the idea is to take different elements as head of sequence and repeats are removed through filter. Complexity of the code shall be fine, since O(n)+O(n or maybe n^2)+O(n)*P(n-1) is dominated by O(n)*P(n-1), where P(n) is the permutation number and cannot be improved, .

    def permute(xs:List[Int]):List[List[Int]] = xs match {
      case Nil => List(List())
      case head::tail => {
        val len = xs.length
        val tps = (0 to len-1).map(xs.splitAt(_)).toList.filter(tp => !tp._1.contains(tp._2.head))
        tps.map(tp => permute(tp._1:::tp._2.tail).map(tp._2.head :: _)).flatten
      }
    }
    

提交回复
热议问题