How can I replace all caracteres by another with all possibilities ?
The function switch progressively all the characters by another.
const globalReplace = (chain) => {
let d = 0;
for (let i = 0; i <= chain.length - 1; i++) {
for (let j = 0; j <= d; j++) {
console.log(chain.slice(0, chain.length - 1 - i), 'X', chain.slice(chain.length - i, chain.length + 1));
}
d++;
}
return;
};
globalReplace('ABCDE');
the result is :
ABCDX ABCXE ABCXE ABXDE ABXDE ABXDE AXCDE AXCDE AXCDE AXCDE XBCDE XBCDE XBCDE XBCDE XBCDE
but i would like :
ABCDX ABCXE ABCXX ABXDE ABXXE ABXXX AXCDE AXXDE AXXXE AXXXX XBCDE XXCDE XXXDE XXXXE XXXXX
Have you any ideas ? I think my function is close to the result.
As you mentioned, order of output strings is not important. Keeping that in mind, I've written a code in python (I'm not well versed with js). You can translate it as you need.
def global_replace(chain, r_chr): # chain is the string to replace, r_chr is character (in your example, 'X')
replaced_strings = []
for i in range(0, len(chain)):
r_str = r_chr * (i+1) # this creates a replace str of length (i+1) with repeated r_chr
for j in range(0, len(chain)-i):
s = chain[:j] + r_str # slice and replace portion of "chain" with r_str
if j+i+1 < len(chain): # string index error check
s += chain[j+i+1:]
replaced_strings.append(s)
return replaced_strings