Just additional information: this is for a game project I’m working on.
I’m trying to make an efficient randomization algorithm that places multiple number of objects (lined up with one another) given a length of how much is available space.
Straight to the problem: Given an available space of length = lengthOfArea, and number of objects to position = numObjects where each object’s length, lengthObject = (lengthOfArea/2) / numObjects. (having so that, the total amount of space that the objects occupy is half of the available space of length).
I’m supposed to look for the center positions of each object and return an array of it.
Here’s my current attempt:
public int[] FindObjectPositions(int lengthOfArea, int numObjects, Random random)
{
int lengthOfObject = (lengthOfArea / 2) / numObjects;
int[] positionsPicked = new int[numObjects];
int minPosition = lengthObject / 2;
int maxPosition = lengthOfArea - (lengthObject / 2);
for (int i = 0; i < numObjects; i++)
{
int newPosition;
do
{
newPosition = minPosition + random.Next(maxPosition - minPosition);
} while (!IsPositionValid(positionsPicked, newPosition, lengthObject));
positionsPicked[i] = newPosition;
}
return positionsPicked;
}
public bool IsPositionValid(int[] positionsPicked, int newPosition, int lengthObject)
{
for (int i = 0; i < positionsPicked.Length; i++)
{
if (Math.Abs(positionsPicked[i] - newPosition) <= (lengthObject / 2))
return false;
}
return true;
}
Basically what I’m doing is I’m constantly randomly finding a valid position for each object. I’m just wondering if it’s inefficient. Also, I’m wondering if I’m ever going to reach a deadlock with this method?
It is possible to deadlock if there is a configuration where no more objects will fit. For instance, if there are 30 spaces and each object is 5-spaces long, the configuration
would have no place that could possibly fit another object, even though there are 15 open spaces!
Say there are
mopen spaces, and each object has widthw. One method that wouldn’t deadlock would be to generate a list ofm-w+1numbers1, 2, ..., m-w, m-w+1. Then choose one at random – this will represents the left-most position of your object. Then remove thew-1numbers to the right and left of that number – this represents the fact that the object iswwide, and no other object of widthwwill fit withinw-1spaces to the left of it.For example, if
m = 20andw = 3,The above method will not deadlock, but it has another issue: it could be possible to have a configuration with (say) 6 objects in it, but the above method might only generate a configuration with 4 or 5 objects in it, and no room for any more. To solve this, rather than choosing random positions for our objects, we can figure out how many empty spaces there should be with 6 objects, and choose random spots for our empty spaces instead (using the above method).
This will give you exactly the number of objects you want, randomly spaced, with no possibility of deadlock.