使用scala的所有重复排列 [英] All permutations with repetition using scala

查看:59
本文介绍了使用scala的所有重复排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种标量方法来给出所有排列而不会重复。我知道这个网站上已经有一些帖子了,但是它们似乎有一个稍微不同的问题。



我正在搜索所有带有重复的排列。
例如:

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

应产生的收益:

  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 ')

很抱歉,如果我的问题已经解决,但找不到。 / p>

预先感谢。



编辑:



我自己的方法(不编译):

  def组合(大小:Int = sym.length):List [List [ T]] = {
大小匹配{
情况0 => List()
情况1 => sym.toList.map(List(_))
情况_ => for(el<-sym)yield el :: Combine(size-1)
}
}

sym是包含所有要组合符号的类的数组成员。

解决方案

  def组合(大小:Int = sym.length):List [List [T]] = {
if(si ze == 0)
List(List())
else {
for {
x<-sym.toList
xs<-groups(size-1 )
}收益x :: xs
}
}


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.

解决方案

def combinations(size: Int = sym.length) : List[List[T]] = {
    if (size == 0)
        List(List())
    else {
        for {
            x  <- sym.toList
            xs <- combinations(size-1)
        } yield x :: xs
    }
}

这篇关于使用scala的所有重复排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆