It is not obvious how we could associate a given arrangement with a score to know how good/bad it is. Here is one way based on your example (items are pulledto generate a solution, may or may not be optimal.First list colors with max. occurrences at the top. Then, pull items from top-most leftcell moving downwards and then to the right when a column has ended)