0

i used this random function to generate the top and the left position. how do i generate the numbers such that the boxes dont overlap with each other.

this.posX = Math.floor((Math.random() * 850) + 1);
this.posY = Math.floor((Math.random() * 450) + 1);

Fiddle: http://jsfiddle.net/ftw68b6f/2/

j08691
  • 204,283
  • 31
  • 260
  • 272
Pratish Shrestha
  • 1,712
  • 4
  • 17
  • 26
  • 1
    try this: http://stackoverflow.com/questions/27732875/randomly-positioned-divs-with-no-overlapping – sdet.ro Dec 05 '15 at 16:35
  • This is a working solution that might suit you: [https://stackoverflow.com/questions/63707669/trying-to-create-x-number-of-random-rectangles-by-iterating-through-loop-but-n](https://stackoverflow.com/questions/63707669/trying-to-create-x-number-of-random-rectangles-by-iterating-through-loop-but-n) – Different Gravity Sep 04 '20 at 08:53

1 Answers1

0

You can't prevent them from overlapping initially, however you can add a while loop that checks whether the current chosen position overlaps with any other box, and if it is the case select a new random location.

If you use this option you have to be aware that when the screen becomes fuller the loop takes longer and longer, and potentially infinitely long if no more boxes fit.

Jeroen C
  • 16
  • 1