Question

My head isn't quite with me and hope somebody can assist...

Let's say I have:

1234567

I wish to generate a list of all possible combinations, the only restrictions are that:

  • A number can only appear once
  • A higher number can't come before a lower number.

So, something like this:

1
2
3
4
5
6
7

12
13
14
15
16
17

123
1234
12345
123456
1234567

134
1345
...
Was it helpful?

Solution

Here is a recursive algorithm, it assumes a range:

function ranges(from,to,soFar){
    console.log(soFar);
    if(from === to){
         return;
    }
    for(var i = from + 1;i <= to;i++){
         ranges(i,to,soFar+i); // append any number that's still possible
    }
}

Usage is ranges(0,7,"") .

At each stage:

  • Print the current result (atm prints the empty string too, you can filter it out)
  • If there are bigger values - iterate over the bigger values and call the function recursively.

OTHER TIPS

@Benjamin Gruenbaum Great solution. Very fast too. I'm still lacking a bit on algorithm knowledge even though I have used such recursions before. Hope you don't mind I modified your code a bit to produce a bi-dimensional array to provide some kind of sorted result:

var results = [];
function ranges(from,to,soFar){
    if(soFar != ''){
        if(!results[soFar.length]){
            results[soFar.length] = [];
        }

        results[soFar.length].push(soFar);
    }
    if(from === to){
         return;
    }
    for(var i = from + 1;i <= to;i++){
         ranges(i,to,soFar+i); // append any number that's still possible
    }
}

ranges(0, 4, '');
console.log(results);

If you have a better way, please do tell.

If you want your results "printed" out, do this:

for(var i = 1; l = results.length, i < l; i++)
{
    console.log(results[i].join('\n'));
}

Replace '\n' for <br/> for HTML. Console log is for reviewing purpose only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top