Evenly distributing all items in a list

Viewed 3898

I have had this problem for a while, still trying to work on a solution.

What is the best possible method for evenly distributing items in a list, with a low discrepancy?

Say we have a list or elements in an array:

Red, Red, Red, Red, Red, Blue, Blue, Blue, Green, Green, Green, Yellow

So ideally the output would produce something like:

Red, Blue, Red, Green, Red, Yellow, Blue, Red, Green, Red, Blue, Green.

Where each instance is "as far away" from another instance of itself as possible...

When, I first attempted trying to solve this problem, I must admit I was naive, so I just used some form of seeded random number to shuffle the list, but this leads to clumping of instances.

A suggestion was start with the item with the highest frequency, so red will be put in position n*12/5 for n from 0 to 4 inclusive.

Then place the next most repeated element (Blue) in positions n*12/3 + 1 for n from 0 to 2 inclusive. If something is already placed there, just put it in the next empty spot. etc etc. However, when jotting it out on paper this doesn't work in all circumstances,

Say the list is only

Red, Red, Red, Red, Red, Blue

It will fail.

Where either option has three same-color adjacencies

Red, Red, Blue, Red, Red, Red
Red, Red, Red, Blue, Red, Red

So please, any ideas, or implementations how to do this would be awesome.

If it matters i'm working on objective-c, but right now all I care about is the methodology how to do it.

6 Answers
Related