3

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!

0

3 Answers 3

5

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()
0
3

You can consider 2D array as 1D array and randomly iterate through it.

def rand_Random(self):
    randomRange = range(self.gridWidth*self.gridHeight)
    shuffle(randomRange)

    for index in randomRange:
        i = index / self.gridWidth
        j = index % self.gridWidth
        if self.grid[i][j] != 'b':
            print i, j
            self.grid[i][j].colour = self.rand_Land_Picker()
0
2

You can do something like:

randomRange = range(w*h)
shuffle(randomRange)

for n in randomRange:
    i = n/w
    j = n%w

Here randomRange basically enumerates all the coordinates from 0 to w*h-1.

Even prettier, i and j, can be found in one statement:

i,j = divmod(n, w)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.