Skip to content Skip to sidebar Skip to footer

Create A Matrix With Random Position

I am creating a matrix with this def letsplay(m,n): matrix = [[ '.' for m in range(10)] for n in range(10)] for sublist in matrix: s = str(sublist) s = s.re

Solution 1:

How about using a probability matrix:

probs = numpy.random.random_sample((10, 10))
data = numpy.empty(probs.shape, dtype='S1')
data.fill('.')
data[probs < threshold] = 'N'

where threshold is a variable that you choose, for example, 0.05 for a 5% chance.

Solution 2:

Not quite sure what prob=5 would mean, probabilities range from 0 to 1? I think there's two parts to your question.

  • change a random element of the matrix

    matrix[random.randrange(10)][random.randrange(10)] = 'N'

  • have a number of elements changed in the matrix, based on a probability.

    import random
    prob = 0.01
    numNs = prob*10*10# because e.g. 1% chance in 10x10 matrix = 1 fieldfor i inrange(numNs):   
      changed = Falsewhilenot changed:
        x = random.randrange(10)
        y = random.randrange(10)
        ifnot matrix[x][y] == 'N': # if not already changed
          matrix[x][y] = 'N'
          changed = True

Post a Comment for "Create A Matrix With Random Position"