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

255
Visualizações
How do you group an array by n and the number of decreasing integers (n-1)? With the output to be the total number of arrays

For example, this is the input array: [2, 1, 4, 4, 3]

From this array, n-1 patterns will be established from left to right.

This output would be the number 7 because the following separate arrays exist after grouping:

[2] [1] [4] [4] [3] - 1 group (n)

[4, 3] - 1 group (n-1)

[2, 1] - 1 group (n-1)

Output: 7 (arrays)

This is what I started so far, but it looks like I just summed everything together.

let numbers = [2, 1, 4, 4, 3];
let sum = numbers.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue;
});

console.log(sum);

It would be appreciated if the solution and an explanation is provided in JavaScript. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Script:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  // remove duplicates
  let unique = [...new Set(numbers)];
  // get length of unique array, then add to the length of filtered unique array where it also contains n-1
  console.log(unique.length + unique.filter(number => numbers.includes(number - 1)).length);
}

Get the number of unique elements then add it to the length of the filtered unique array where it also contains n-1.

Output:

output

If you want to get the arrays:

function myFunction() {
  let numbers = [2, 1, 4, 4, 3];
  let unique = [...new Set(numbers)];
  var arrays = [];
  unique.forEach(number => {
    arrays.push([number]); 
    if(numbers.includes(number - 1))
      arrays.push([number, number-1])
  });

  console.log(arrays.length)
  console.log(arrays)
}

output2

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