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

189
Vistas
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 Respuestas
Responde la pregunta

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