Code to enumerate permutations in Scala

后端 未结 11 2055
臣服心动
臣服心动 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:30

    Maybe this thread is already well-saturated, but I thought I'd throw my solution into the mix:

    Assuming no repeat elements:

    def permList(l: List[Int]): List[List[Int]] = l match {
       case List(ele) => List(List(ele))
       case list =>
         for {
           i <- List.range(0, list.length)
           p <- permList(list.slice(0, i) ++ list.slice(i + 1, list.length))
         } yield list(i) :: p
    }
    

    With repeat elements, preventing duplicates (not as pretty):

    def permList(l: List[Int]): List[List[Int]] = l match {
      case List(ele) => List(List(ele))
      case list =>
        for {
          i <- List.range(0, list.length)
          val traversedList = list.slice(0, i)
          val nextEle = list(i)
          if !(traversedList contains nextEle)
          p <- permList(traversedList ++ list.slice(i + 1, list.length))
        } yield list(i) :: p
    }
    

    It's potentially not the most "list-y", given that it uses slice and an index on the list, but it's rather concise and a slightly different way of looking at it. It works by singling out each element in the list and computing the permutations of what's remaining, and then concatenating the single element to each of those permutations. If there's a more idiomatic way to do this, I'd love to hear about it.

提交回复
热议问题