Nate
Nate

Reputation: 2048

algorithm to evenly space objects across containers

I have a line of 12 cups and I will receive a random number of balls to be placed in those cups. I could receive between 1 and 12 balls (inclusive). No matter the number of balls I receive, I want to evenly space them across the line of cups. Each cup may only contain one ball.

The concept of "even" is up for debate. For instance, if I get 6 balls, I can space them every-other cup, but if I get 7 balls, the location of that 7th ball isn't terribly important to me, as long as it follows a logical pattern. Similarly, the location of the extra space between balls when I only have 5 balls is not important to me either.

So, is anyone familiar with an distribution algorithm of this sort? I've cobbled something together, but it's so bad that it will never see the light of day.

enter image description here

Upvotes: 2

Views: 660

Answers (3)

Fattie
Fattie

Reputation: 12278

As Matt already said, just .. A very simple solution is, if the ball is B take the nearest integer to B plus a half times 12 divided by the number of balls in the run.


The more smart ass way to do it, and you don't even have to know how many balls there are in total, is: take a ball; find the longest run of holes: put the ball in a random position in that run. Just repeat that until you run out of balls. In a random way and over time, they will be evenly distributed and, uh, "random" looking. This is how you do it if you have lots of slots and lots of balls. Interestingly, you can abstract it to more than one dimension.

Upvotes: 1

Hasan Delibaş
Hasan Delibaş

Reputation: 500

Sorry i can not tell you this in English. But i can help with code and math.

F(x,b)  ->  {0,1}
x € [0,11] , b  € [1,12]  

F (x,b) is : this is blue box or white box function. x are boxes; b are balls.

int F(x,b){
   if (    (int)(x % 12/b)   == 0 ) return 1;
   else return 0;
}

**Second Way*

float i = 0;
int b = 1; // Balls
while(i<12){
   printf( '%d. box', (int) i);
   i +=  (float)12 /(float)b ;
}

You can see this algorithm in https://jsfiddle.net/k0r18yba/

Upvotes: 0

Matt Timmermans
Matt Timmermans

Reputation: 59323

Normally if you get N balls, you'd put the ith ball (counting from zero) in bucket floor((i+0.5)*12/N) (also counting from zero), or something like that

Upvotes: 2

Related Questions