We’ve all been there, trying to juggle two or more things for either split testing or just because you want some variety. This came up recently for me with juggling advertising networks and I wrote some simply code to handle it. The premise is simple, you assign weights to the items that you want to distribute, tally up the weights, generate a random number and grab your results. With the following code, I recommend that the weights total 100, but they don’t have to (you’ll have to do the math to determine the percentage if you don’t keep it to 100)
It’s not an exact science, but it gets the job done within reason. I am using this code in production but I have some ideas on how to avoid looping over all of the items (which could get crazy if you had thousands and thousands of items).