Tengo un problema en ejecución ahora que es: necesito una función que encuentre el número más alto formado por dígitos consecutivos dentro de ese número que recibí por el parámetro. Por ejemplo: si mi entrada es 1235789, mi salida debería ser 789. Si mi entrada es 123689, mi salida debería ser 123.
function getbiggestNumber(numberInput) { const numberString = numberInput.toString(); // turned into string const temporaryResult = []; // create the array of possible solutions which i'd go through to find the highest value inside of it for (let i = 0; i < numberString.length; i += 1) { const temporary = [numberString[i]]; // create a temporary answer that would serve as a base for (let x = i + 1; x < numberString.length; x += 1) { const subResult = Number(numberString[i]) - Number(numberString[x]); // the result of the current number minus the following number if (subResult === -1) { // if they are in a sequence this should be -1 temporary.push(numberString[x]); // pushing this number to that temporary answer } // here should be some condition for it to keep running, instead getting into another number of for loop } temporaryResult.push(temporary); // pushing that temporary answer to the result, so I could keep track of it } console.log(temporaryResult); // checking the output }El problema es que este código solo proporciona dos dígitos dentro de una matriz, y esa fue la única forma que encontré para hacerlo. Estaría muy agradecido si alguien pudiera darme una luz sobre esto. ¡Gracias!
Eso parece un poco innecesariamente complicado. Simplemente dividiría la cadena en fragmentos según los dígitos secuenciales, luego llamaría a Math.max en todos.
const getBiggestNumber = (numberInput) => { const digits = [...String(numberInput)].map(Number); const chunks = []; let lastDigit; let chunk = []; for (const digit of digits) { if (lastDigit === digit - 1) { // Continuation of sequence chunk.push(digit); } else { if (chunk.length) chunks.push(chunk); // New sequence: chunk = [digit]; } lastDigit = digit; } chunks.push(chunk); return Math.max( ...chunks.map(chunk => Number(chunk.join(''))) ); }; console.log(getBiggestNumber(1235789));Otro enfoque:
const largestStreak = (input) => Math .max (... [...String (input)] .map (Number) .reduce ( (a, d, i, xs) => d == a .at (-1) .at (-1) + 1 ? [... a .slice (0, -1), [... a .at (-1), d]] : [... a, [d]], [[]] ) .map (ns => Number (ns .join ('')))) console .log (largestStreak (1235789)) console .log (largestStreak (1235689))Esto pasa por los siguientes pasos:
input :
1235789 [...String (input)] .map (Number) :
[1, 2, 3, 4, 7, 8, 9]reducir acumulador, paso a paso:
[[]] [[], [1]] [[], [1, 2]] [[], [1, 2, 3]] [[], [1, 2, 3], [5]] [[], [1, 2, 3], [5], [7]] [[], [1, 2, 3], [5], [7, 8]] [[], [1, 2, 3], [5], [7, 8, 9]] .map (ns => Number (ns .join (''))) :
[0, 123, 5, 789] Math .max (...) :
789