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

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

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 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