0

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

tudoricc
  • 709
  • 1
  • 12
  • 31

1 Answers1

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.

  1. Take the input array and step over it
  2. 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
  3. Push the number to result
  4. 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