I am trying to generate all possible numbers starting with a vector of digits that I don't want to occur more than how many times they are in that vector . My first ideea was backtracking but how.... For example: 3 7 5 => 3 5 7 35 37 53 57 73 75 357 375 537 573 735 753
Asked
Active
Viewed 215 times
1 Answers
2
Basically I would use a recursive function that selects each number from the vector appends that number to the result and use a reduced vector and the number as "prefix" in the recursive call. The result I would filter afterwards for dublicates with a unique function like Unique values in an array
function selectOne(data,res,prependNumber){
var current,reduced,i,len;
for(i=0,len = data.length;i<len;i++){
current = data[i];
if(prependNumber!==false){
current = prependNumber+ '' + current;
}
reduced = data.slice(0);
reduced.splice(i,1);
res.push(parseInt(current));
selectOne(reduced,res,current);
}
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
Sample call
var test = [3,5,7];
var res = [];
selectOne(test,res,false);
console.log(res.filter( onlyUnique ));
The algorythm works following.
- Take the input array and step over it
- generate a new array reduced by the element in this iteration
- I use .slice(0) to clone the actual input array, because slice generates a new array starting with the given index
- I use .splice to extract 1 Element starting at position i
- Push the number to result
- Use the reduced array to call the function again and use the current number in this iteration, to prepend that when I drag the next number and push that to the result
E.g. Take the input array [3,5,7]. I iterate over it. First I grab 3 and generate the reduced array [5,7]. I push the 3 to the result and call my function recursivelly with this array and 3 as prependNumber. In the loop I then first select the 5, but because I have given the prependNumber I do not push 5 to the result but 35 and have a reduced array [7]. And so on.
Following recursion will take place:
selectOne - level 1
res: [3]
selectOne - level 2
res: [3,35]
selectOne - level 3
res: [3,35,357]
selectOne - level 2
res: [3,35,357,37]
selectOne - level 3
res: [3,35,357,37,375]
selectOne - level 1
res: [3,35,357,37,375,5]
selectOne - level 2
res: [3,35,357,37,375,53]
selectOne - level 3
res: [3,35,357,37,375,53,537]
selectOne - level 2
res: [3,35,357,37,375,53,537,57]
selectOne - level 3
res: [3,35,357,37,375,53,537,57,573]
.
.
.

Community
- 1
- 1

AthanasiusKirchner
- 188
- 7
-
what does data.slice(0) do?and splice(i,1) and why is there a root!=false? – tudoricc Apr 14 '14 at 16:26
-
I changed the variable name because it was a bit confusing. – AthanasiusKirchner Apr 14 '14 at 18:49