Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All permutations with repetition using scala

I am looking for the scala way to give all permutations without repetitions. I know there are some postings on this site already but they seem to have a slightly different problem.

I am searching for all permutations with repetitions. For example:

combine(List('A','C','G'))

Should yield:

List(List('A'.'A','A'),List('A'.'A','C'),List('A'.'A','G'),List('A'.'C','A'),
List('A'.'C',''C), ... List('G'.'G','G')

I am sorry if my problem is already solved but I was not able to find it.

Thanks in advance.

EDIT:

My own approach (doesn't compile):

def combine(size: Int = sym.length) : List[List[T]] = {
  size match {
    case 0 => List()
    case 1 => sym.toList.map(List(_))
    case _ => for (el <- sym) yield el :: combine(size-1)
  }
}

sym is an array member of a class which contains all the symbols to be combined.

like image 690
peri4n Avatar asked Sep 19 '11 17:09

peri4n


People also ask

What is combination with repetition?

2. Combinations with Repetition. Assume that we have a set A with n elements. Any selection of r objects from A, where each object can be selected more than once, is called a combination of n objects taken r at a time with repetition.

What is permutation without repetition?

The permutations without repetition of elements are the different groups of elements that can be done, so that two groups differ from each other only in the order the elements are placed.


1 Answers

With Scalaz:

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> def combine[A](xs: List[A]): List[List[A]] = {
     |   xs.replicate[List](xs.size).sequence
     | }
combine: [A](xs: List[A])List[List[A]]

scala> combine(List('A', 'C', 'G'))
res47: List[List[Char]] = List(List(A, A, A), List(A, A, C), List(A, A, G), List
(A, C, A), List(A, C, C), List(A, C, G), List(A, G, A), List(A, G, C), List(A, G
, G), List(C, A, A), List(C, A, C), List(C, A, G), List(C, C, A), List(C, C, C),
 List(C, C, G), List(C, G, A), List(C, G, C), List(C, G, G), List(G, A, A), List
(G, A, C), List(G, A, G), List(G, C, A), List(G, C, C), List(G, C, G), List(G, G
, A), List(G, G, C), List(G, G, G))
like image 170
missingfaktor Avatar answered Nov 15 '22 20:11

missingfaktor