简体   繁体   中英

generating random list of given numbers with limitations and certain length with python

I want to generate a binary matrix (16*15) of random 1s and 0s with these conditions:

  • no more than 2 consecutive equal numbers in each row.
  • if there are consecutive equal numbers in each row no more than 3 pairs of them are allowed.
  • the quantity of 1s and 0s in each row must be 8 and 7 or 7 and 8 respectively.

I have this code for generating a random list but I don't know how to add the conditions at the random part.

import random
import numpy as np

arr_len = 15
num_ones = 8

pattern = np.zeros(arr_len, dtype=int)
idx = np.random.choice(range(arr_len), num_ones, replace=False)
pattern[idx] = 1
print (pattern)

In this case it is easy enough to create a list of all possible such rows (there are only 504) and then creating the matrix from random rows.

The following code does that by looking at every possible row, which it generates by iterating through the numbers 0 to 2^15-1 in binary format. It then checks the three conditions, and stores the valid rows. To generate the matrix, it then draws 16 random rows.

def BinaryString(n):
    s = bin(n)[2:]
    return '0'*(15-len(s)) + s

validRows = []
for binaryNum in range(2**15):
    s = BinaryString(binaryNum)

    #Check Condition 3
    if np.sum([num == '0' for num in s]) not in [7,8]:
        continue

    #Check Condition 1
    hasTriple = False
    for i in range(13):
        if s[i] == s[i+1] and s[i+1] == s[i+2]:
            hasTriple = True
            break
    if hasTriple:
        continue

    #Check Condition 2
    doubles = np.sum([s[i] == s[i+1] for i in range(14)])
    if doubles > 3:
        continue

    #If it is good, append it to the list
    validRows.append([int(i) for i in s])

validRows = np.vstack(validRows)

def CreateMatrix():
    rows = np.random.randint(0,len(validRows),16)
    return np.vstack([validRows[i] for i in rows])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM