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

120
Views
How to randomize an array, leaving the items that are the same far from each other?

Basically I have an array where there are similar items close by, but I would like to find a way where I leave these items that are the same apart from each other ex:

var array = [1,2,3,3,4]; 

var myWishArray = [1,2,3,4,3];
||
var myWishArray = [3,2,3,4,1];
||
var myWishArray = [3,2,3,1,4];
...

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If it's enough that two equal numbers are never neighbors, then you can

  • sort the list
  • fill a new array with these numbers in two passes, leaving a space of one

a = [1, 1, 1, 1, 2, 3, 2, 3, 4, 4, 4];
a.sort();
b = Array(a.length);
for (i = 0; i < a.length; i ++) {
    if (i * 2 < a.length) {
        b[i * 2] = a[i];
    } else {
        start = i - Math.ceil(a.length / 2)
        b[start * 2 + 1] = a[i];
    }
}
console.log(b);

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!