Algorithm for positioning random elements on an infinite plane

I'm looking for an algorithm where I can set pseudo-random positions within a given viewport (top, left, width) without storing those positions. Let's say I have a viewport (0, 0) to (100, 100). Then I will find elements in (67, 25), (36, 42) and (1, 2). If I changed this viewport from (-50, -50) to (50, 50), I would still find (36, 42) and (1,2), but then I could also find it on (- 14, 7) and (-32, -20). I don't know how I can make it clearer.

+3


source to share


1 answer


An example of working with integers. It can also be changed to float.

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 entire plane is covered with squares containing random points depending on the square.



You will find the location of the bottom left square ( sx

, sy

), then you compute the locations of all the squares that are needed for the selected window ( bx

, by

). You initialize the random number generator and then generate any required squared points ( px

, py

). But in fact, only those points that are inside the window are counted.

Just for inspiration.

+2


source







All Articles