Mi código funciona y necesito ayuda para averiguar cómo optimizarlo. Si es posible, no me des ningún código, solo consejos para optimizarlo, por favor.
Las reglas para el rompecabezas son:
Ejemplo de entrada:
triplets1 = [ ['t','u','p'], ['w','h','i'], ['t','s','u'], ['a','t','s'], ['h','a','p'], ['t','i','s'], ['w','h','s'] ] Salida esperada: "whatisup"
Se me ocurrió este código, que funciona. Selecciona las primeras letras que no están precedidas por ninguna otra en las matrices en las que se colocan, las elimina, las concatena en la palabra final y continúa haciéndolo hasta que todas las matrices estén vacías. Sin embargo, el código no se acepta porque está excediendo el límite de tiempo.
function recoverSecret(triplets) { let secretWord = '', character = ''; let notEmpty = true; let size = triplets.length; //it loops until array is empty while(notEmpty) { notEmpty = false; for (let i = 0; i < size; i++) { for (let j = 0; j < triplets[i].length; j++) { if (character) j = 0; //everytime a character is included, this condition is truthy, so you have to go back to the start of the array because the character was removed last iteration character = triplets[i][j]; let remove = []; //this array will have the positions of the letter to remove in the removal cycle for (let k = 0; k < size; k++) { if (character == triplets[k][0]) remove.push(k); //if the letter is in the triplet and it's not the first position, then it isn't the letter we're looking for, so character equals to '', otherwise it will be the letter which will be added to the secretWord string if (k != i && (triplets[k].includes(character))) { if (character != triplets[k][0]) { character = ''; break; } } } secretWord += character; if (character) { //if character is not '', then a removal loop is done to remove the letter because we just found its place for (x of remove) { triplets[x].shift(); } } // if (triplets[i].length == 0) break; } if (triplets[i] != 0) notEmpty = true; //if every triplet is empty, notEmpty remains false and while loop is over } } return secretWord; }Si es posible, no quiero ningún código, solo consejos sobre optimización, por favor.