Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!