A simple DFS can get you the permutations that you are looking for. Basically, you have to replace the first occurrence of ?
with the operator and recursively call the function again until there is no ?
in the string.
Here we can make use of the replace() function as it leaves the original string unchanged.
Code
function dfsPermute(s){
// If the ? dosent exist then its index will be -1
// In that case print it to the console
if(s.indexOf('?') === -1) {
console.log(s);
}
else {
let s1 = s.replace('?', '+')
dfsPermute(s1);
let s2 = s.replace('?', '-')
dfsPermute(s2);
let s3 = s.replace('?', '*')
dfsPermute(s3);
let s4 = s.replace('?', '/')
dfsPermute(s4);
}
}
dfsPermute('2?5?4');
Output
2+5+4
2+5-4
2+5*4
2+5/4
2-5+4
2-5-4
2-5*4
2-5/4
2*5+4
2*5-4
2*5*4
2*5/4
2/5+4
2/5-4
2/5*4
2/5/4
Note: If there are x
number of ?
characters in the string, the number of possible permutations are going to be 4^x
which can grow very quickly