Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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));

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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 ?

about 4 years ago · Santiago Trujillo Denunciar

0

I modified your code so that it suits the needs, however there may be some bugs or exceptions not handled yet, but it can give you a hint that how you are going to solve the problem.

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'];

let randomLeter = (excluded) =>
{
   let letter = false;
   do
   {
       letter = letters[Math.floor(Math.random() * 26)];
   }
   while(excluded.includes(letter));
   
   return letter;
}

let getIndices = (s, t) => {
  return [...s].flatMap((char, i) => (char === t ? i : []));
};

let Solve = (riddle) => 
{
    riddle = [...riddle];
    //get the locations of all ? in the string
    let all = getIndices(riddle, '?'); 
    
    for(let i = 0; i < all.length; i++)
    {
        //exluding characters before and after the ?
        let excluded = [riddle[all[i] - 1], riddle[all[i] + 1]];

        riddle[all[i]] = randomLeter(excluded);
    }
    
    return riddle.join("");
};

let riddle = 'ab?d?f';
document.getElementById('riddle').innerHTML = 'The Riddle ' + riddle;
document.getElementById('solution').innerHTML = "Solution " + Solve(riddle);
<h2 id="riddle"></h2>
<h4 id="solution"></h4>

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda