Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for positioning random elements on an infinite plane

Tags:

algorithm

I'm looking for an algorithm where I can establish psuedorandom positions within a given viewport (top, left, width height) without having to store those positions. Say I have a viewport from (0, 0) to (100, 100). I would then find elements at (67, 25), (36, 42), and (1, 2). If I were to change that viewport to from (-50, -50) to (50, 50), I would still find (36, 42) and (1,2) but I would then also maybe find one at (-14, 7) and (-32, -20). I don't know how I can make this clearer.

like image 455
Jordan Avatar asked Aug 08 '26 20:08

Jordan


1 Answers

Example working on integers. It could be modified to floats, too.

import random

STEP = 10  # size of square with random points
COUNT = 6  # number of random points in the square

def get_points(x1, y1, x2, y2):
    points = []
    sx = (x1 // STEP) * STEP
    sy = (y1 // STEP) * STEP
    for bx in range(sx, x2, STEP):
        for by in range(sy, y2, STEP):
            random.seed(bx + by)
            for i in range(COUNT):
                px = bx + random.randrange(STEP)
                py = by + random.randrange(STEP)
                if x1 <= px < x2 and y1 <= py < y2:
                    points.append((px, py))
    return points

print get_points(0, 0, 10, 10)
print get_points(0, 0, 100, 100)

The whole plane is covered with squares containing random points depending on the square location.

You find the location of the bottom-left square (sx, sy), then you calculate locations of all squares that are needed for the selected window (bx, by). You initialize the random number generator and then generate all necessary points in the square (px, py). But only points that are inside the window are actually considered.

Just for inspiration.

like image 165
dlask Avatar answered Aug 11 '26 11:08

dlask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!