I want to display random numbers inside a div at random positions without overlapping. I am able to display random number at random position but its going outside the box an
If the number of divs you need to create is small enough (i.e. you're not risking that they won't fit) then a simple algorithm is:
(x0, y0)-(x1, y1)
in code
var selected = [];
for (var i=0; i= selected[i].x1 ||
y0 >= selected[i].y1 ||
x1 <= selected[i].x0 ||
y1 <= selected[i].y0)) {
i++;
}
if (i == selected.length) {
// Spot is safe, add it to the selection
selected.push({x0:x0, y0:y0, x1:x1, y1:y1});
break;
}
// The choice collided with a previously added div
// just remain in the loop so a new attempt is done
}
}
In case the elements are many and it's possible to place n-1
of them so that there's no position where to put n
-th element then things are a lot more complex.
For the solution of the 1-dimensional version of this problem see this answer.