Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 遍历Int集的算法_Algorithm_Scala - Fatal编程技术网

Algorithm 遍历Int集的算法

Algorithm 遍历Int集的算法,algorithm,scala,Algorithm,Scala,我不确定这是不是问这样一个问题的合适地方。我就试试看 问题: 假设val阈值:Int和val大小:Int 我正在寻找一种有效的算法来遍历所有可能的x:Set[Int]其中x.sum

我不确定这是不是问这样一个问题的合适地方。我就试试看

问题:

假设
val阈值:Int
val大小:Int

我正在寻找一种有效的算法来遍历所有可能的
x:Set[Int]
其中
x.sum
x.size==n
。只应考虑大于0的整数。这当然是有限的可能性

我已经尝试过开发一个,但即使是较小的投入,也需要永远


提前感谢。

您可以非常轻松地递归生成它们。这里有一些Python代码可以实现这一点,但它应该直接转换为Scala

def sets(n, threshold, atleast=1):
    if threshold <= n * (n + atleast * 2 - 1) // 2: return
    if n == 0:
        yield []
        return
    for i in xrange(atleast, threshold):
        for s in sets(n - 1, threshold - i, i + 1):
            yield [i] + s

print list(sets(4, 15))
def设置(n,阈值,至少=1):

如果threshold,如果有人感兴趣,我将在Scala中发布我对上述算法的实现:

def generatePossibilities(n: Int, threshold: Int) = {
    def sets(n: Int, threshold: Int, atleast: Int = 1) : Set[Set[Int]] = {
      if(threshold <= n * (n + atleast * 2 - 1) / 2) {
        Set.empty[Set[Int]]
      } else if(n == 0) {
        Set(Set.empty[Int])
      } else {
        (for(i <- atleast until threshold;
             s <- sets(n - 1, threshold - i, i + 1)) yield s + i)(collection.breakOut)
      }
    }
    sets(n, threshold)
}
def生成可能性(n:Int,阈值:Int)={
def集合(n:Int,阈值:Int,至少:Int=1):集合[Set[Int]={

if(threshold)你能提供你的示例代码吗?所以你有一个可遍历的[Set[Int]]?它更像一个Set[Set[Int]]最后。看起来很有希望,我会很快尝试一下。在
if threshold@Kigyo的情况下,该条件捕获了这样一个想法,即如果阈值太低,或者n太大,那么就没有满足该条件的整数集。(表达式为sum(i=atleast to atleast+n-1)in=0,阈值=0
是错误的。您从我的代码中删除了一个条件,它既捕获了此边缘大小写(这可能并不重要),又消除了许多不会产生结果的递归调用。例如,try(n=100,阈值=5051)带和不带额外子句。在不知道Scala的情况下,我怀疑缺少的代码是
if(threshold Ok thx)。现在我明白你的意思了。我认为这只是对初始
n
treshold
的一般检查。没有它也可以工作。编辑了我的答案。