Generate numbers in side div at random position without overlapping

前端 未结 3 1140
孤城傲影
孤城傲影 2021-01-18 10:00

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

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 10:49

    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:

    • pick a random position (x0, y0)-(x1, y1)
    • check if any previously selected rect overlaps
    • if none overlaps then add the rect, otherwise loop back and choose another random position

    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.

提交回复
热议问题