Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly iterating through a 2D list in Python

My first attempt to accomplish this resulted in:

def rand_Random(self):
    randomRangeI = range(self.gridWidth)
    shuffle(randomRangeI)
    randomRangeJ = range(self.gridHeight)
    shuffle(randomRangeJ)

    for i in randomRangeI:
        for j in randomRangeJ:
            if self.grid[i][j] != 'b':
                print i, j
                self.grid[i][j].colour = self.rand_Land_Picker()

Which has the issue of going through one inner list at a time:

[1][1..X]

[2][1..X]

What I'd like to be able to do is iterate through the 2d array entirely at random (with no repeats).

Anyone have any solutions to this problem?

Edit: Thanks for the replies, it appears the way I view 2d arrays in my mind is different to most!

like image 548
Darkstarone Avatar asked Jun 11 '26 13:06

Darkstarone


1 Answers

Create an array with all possible pairs of coordinates, shuffle this and iterate through as normal.

import random
coords = [(x,y) for x in range(self.gridWidth) for y in range(self.gridHeight)
random.shuffle(coords)
for i,j in coords:
    if self.grid[i][j] != 'b':
        print i, j
        self.grid[i][j].colour = self.rand_Land_Picker()

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!