Algorithm to cross int sets

advertisements

I'm not sure if this is the right place to ask such a question. I will just give it a shot.

Problem:

Assume val threshold: Int and val size: Int.

I'm looking for an efficient algorithm to traverse all possible x: Set[Int] where x.sum < threshold and x.size == n. Only Ints greater than 0 should be considered. This is of course a finite number of possibilities.

I have already tried to develop one, but even for smaller inputs it takes forever.

Thanks in advance.


You can generate them recursively quite easily. Here's some code in Python that does it, but it should translate directly to 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))