Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda