Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I replace all '?' in the phrase with a random letter but the letter used cannot repeat twice in a row?

For example say you have the string ‘ab?d?f’ and you must grab the string and replace it with any random letters in the ‘?’ like ‘abcdef’ or ‘abjdlf’ but it cannot be ‘abbdef’ or ‘abcdff’.

I have attempted this below:

const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

const randomLeter = () => letters[Math.floor(Math.random() * 26)];

const riddle = 'ab?d?f';

let pickedLetter;
let solvedRiddle;

function solve(riddle) {
    for (let i = 0; i < riddle.length; i++) {
        if (riddle[i] === '?' && !(riddle[i-1] === randomLeter) && !(riddle[i+1] === randomLeter)){
            console.log('Changing to letter');
            solvedRiddle = riddle.replace('?', pickedLetter);
        }
        pickedLetter = randomLeter();
        console.log(i, riddle[i], pickedLetter);
    }
    return solvedRiddle;
}
// The above only returns the first '?' changed but leaves the second one unchanged ... ??? Why can I not change the value of solvedRiddle a second time inside the loop? I can see by my log that it reads at true, but the value won't be re-written.
console.log(solve(riddle));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

function solve(riddle) {
    for (let i = 0; i < riddle.length; i++) {
        if (riddle[i] === '?'){
            console.log('Changing to letter');
            let pickedLetter = randomLeter();
            while (riddle[i-1] === pickedLetter || riddle[i+1] === pickedLetter) {
              pickedLetter = randomLeter();
            }
            riddle = riddle.replace('?', pickedLetter);
        }
    }
    return riddle;
}

Also, it’s because u update and return solvedRiddle. Your original riddle string is not updated, so in the second run, it is still changing the first ?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading