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

213
Visualizações
Cómo crear un generador de anagramas usando JS con recursividad

Así que he estado tratando de crear una función que imprima todos los anagramas posibles para una cadena dada, input:abc output:abc,acb,bac,bca,cab,cba Pero no puedo completarlo, así que el problema es que yo no puede insertar la primera letra en un índice específico en una cadena, ¿alguna solución?

 function anagram(str) { if (str.length === 1) return str[0]; let collection = []; let subStr = str.slice(1, str.length); let subStrAnagram = anagram(subStr); for (let i = 0; i < subStrAnagram.length; i++) { for (let j = 0; j < subStrAnagram[i].length; j++) { let copy = new String(subStrAnagram[i]); } } return collection; } console.log(anagram("avc"));
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Qué tal esto:

 function anagram(str) { // Edge cases if (str.length == 0) return []; if (str.length == 1) return [str]; let collection = []; anagramRecursive(str, "", collection); return collection; } function anagramRecursive(str, prev, collection) { if (str.length == 0) { collection.push(prev); return; } let alreadyUsed = []; for (let i = 0; i < str.length; i++) { // If the character at str[i] has already been used at this level, // skip it to avoid generating duplicate solutions if (alreadyUsed.includes(str[i])) { continue; } alreadyUsed.push(str[i]); const current = prev + str[i]; const newStr = str.slice(0, i) + str.slice(i + 1); anagramRecursive(newStr, current, collection); } }

Se actualizó para incluir una verificación que evita que se generen soluciones duplicadas.

about 4 years ago · Santiago Trujillo Relatório

0

La siguiente solución asume que el anagrama es una sola palabra sin espacios.

La explicación del código está en línea.

 function anagram(original, str, collections) { let splitted = str.split(''); // convert the string to array. Why? Its easy to handle for(let i =0; i < (splitted.length - 1); i++){ // Run a for loop till last but 1 character. const char = splitted[i]; // copy the character at that index splitted.splice(i, 1, str[i+1]); // shift the immediate next character to index splitted.splice(i+1, 1,char); // insert the copied character to the position of the next const joined = splitted.join(''); // join the splitted if(collections.indexOf(joined) === -1){ // confirm the string is not previously formed collections.push(joined) // put it inside the collection } } const lastCollection = collections[collections.length-1]; // take the last collection if(lastCollection !== original){ // compare it with the original, if not matches, call anagram function again return anagram(original, lastCollection, collections); } return collections; // else return the collections } console.log(anagram("abc", "abc", []));

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