distribute types of item in an array as evenly as possible

108 Views Asked by At

there are a different number of items of each type. Suppose I have items 'a', 'b' and 'c'. have an array of these items ['a','b','b','c','c','c','a','c'] for example and i want to re position the items in the array so they all get visited as often as possible in proportion to how many there are.

Any ideas how I do this. I want it so i can take a load handling factor for my servers and simply build an array of host id's so I spread the load as evenly as possible not send 5 clients to one server in a row then 3 clients to another in a row. If you get what i mean.

1

There are 1 best solutions below

0
On

if you want to do a load balancer, you can use linq to get the lookup and get the count for the current load, then assign the new client to the lowest count.

public static int minLoad(List avg) { var count = avg.ToLookup(x => x).Select(x => new { item = x.Key, Counter = x.Count() }); var minclient = count.OrderByDescending(x => x.Counter).First().item; return minclient; } public static string minLoadstr(List avg) { var count = avg.ToLookup(x => x).Select(x => new { item = x.Key, Counter = x.Count() }); var minclient = count.OrderByDescending(x => x.Counter).First().item; return minclient; } public static void Main(string[] args) { List clientsload = new List { 1, 1, 2, 2, 3, 3 }; int minclient = minLoad(clientsload); List clientsloadstr = new List { "A","A","C","B","C","C" }; string minclientstr = minLoadstr(clientsloadstr); }