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

261
Vistas
Math Challenge print the next largest number after shuffling using javascript

Have the function nextLargest(num) take the num parameter being passed and return the next number greater than num using the same digits. For example: if num is 123 return 132, if it's 12453 return 12534. If a number has no greater permutations, return -1 (ie. 999).

Examples

Input: 11121
Output: 11211
Input: 41352
Output: 41523
var permute = (function () {
    return permute;

    function permute(list) {
        return list.length ?
            list.reduce(permutate, []) :
            [[]];
    }
    
    function permutate(permutations, item, index, list) {
        return permutations.concat(permute(
            list.slice(0, index).concat(
            list.slice(index + 1)))
            .map(concat ,[item]));
    }
    
    function concat(list) {
        return this.concat(list);
    }

}());

console.log(JSON.stringify(permute([1,2,3,4])));

my output : [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]]

expected output :

Input: 11121
Output: 11211
Input: 41352
Output: 41523
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Assuming the permute function as given that you shared in your question, the following straightforward approach should solve the question.

It is not very efficient, however. Probably, a better strategy could be found working with a cleverly chosen sequence of transpositions only.

function nextLargest(input) {
  let x = input.toString();
  let p = permute([...x]);
  let result = Infinity;
  for (let n of p) {
    let y = n.join('')*1;
    if (y > input && y < result) result = y; 
  }
  return result < Infinity ? result : -1;
}
  
console.log(nextLargest(1234));  // <<< gives 1243
about 4 years ago · Juan Pablo Isaza 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