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

190
Visualizações
How to shuffle an array with duplicate items, but duplicates can't be back to back

Given an array [1, 2, 2, 3, 4, 4, 5], is it possible to shuffle the array while preventing the duplicates to be next to each other?

For example:

  • [1, 2, 3, 4, 2, 5, 4] is an acceptable solution.
  • [1, 2, 3, 4, 4, 2, 5] is not an acceptable solution since 4 is next to another 4

This seems like a simple question but after thinking about it, the solution seems complicated. Any help is greatly appreciated, thanks!!

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

0

If you don't care about the execution time of the algorithm, just shuffle a few times until you get the result you want

let arr = [1, 2, 2, 3, 4, 4, 5];

const hasDublicateItems = (arr) => arr.some((v, i, a) => v === a[i+1]);

while (hasDublicateItems(arr)) 
  arr = arr.sort(() => (Math.random() > .5) ? 1 : -1);

console.log(arr);
.as-console-wrapper{min-height: 100%!important; top: 0}

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