Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a random int just be itself once in loop

So.. im working on this loop:

stuff_so_far = [intl_pt]

for i in range(0, num_pts - 1):
    rdm = random.randint(0, len(points_in_code) - 1)
    a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2
    b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2
    stuff_so_far.append((a, b))

Basically what i want to achive is to get a random index for "points_in_code" every time the code loops. It is doing that now, but what i want to know is, how do i make it not randomly repeat a number? As in, if in the first iteration of the loop rdm gets set to 1, and then in the second iteration of the loop rdm gets set to 3, and in some cases, rdm can be set to 1 again in the third itertion. How do i make it not be 1 again (as long as the loop is still going)?

Ive tried everything i know and searched online but i found nothing, how do i make that happen without altering my code too much? (im new to programming)
I know each time i call random.randint(), i am creating a single random number, it does not magically change to a new random not used before number everytime the loop iterates.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use an Array for keep track of which random number you already used. You only need to regenerate the random number if you get one which you already had.

stuff_so_far = [intl_pt]
tracking_num = [] # keeps track of the random number that was alreadey used.


for i in range(num_pts - 1): # small tip you can create a for-loop without the zero in the beginning.
    # while loop in which a number will be regenerated if the current random number
    # is contained in the 'tracking_num' array.
    rdm = random.randint(0, len(points_in_code) - 1)
    while tracking_num.__contains__(rdm):
        rdm = random.randint(0, len(points_in_code) - 1)

    a = (stuff_so_far[i][0] + points_in_code[rdm][0]) // 2
    b = (stuff_so_far[i][1] + points_in_code[rdm][1]) // 2
    stuff_so_far.append((a, b))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading