简体   繁体   中英

how do I produce unique random numbers as an array in Python?

I have an array with size (4,4) that can have values 0 and 1, so I can have 65536 different arrays. I need to produce all these arrays without repeating. I use wt_random=np.random.randint(2, size=(65536,4,4)) but I am worried they are not unique. could you please tell me this code is correct or not and what should I do to produce all possible arrays? Thank you.

you can use itertools.product with repeat=16 to generate all patterns, then just reshape them to (4,4) .

try this:

import numpy as np
from itertools import product

wt_random = np.array([np.array(p).reshape((4, 4)) for p in product((0, 1), repeat=16)])
np.random.shuffle(wt_random)

print(wt_random.shape)
print(wt_random[1234])

Output: (shows the shape is correct, and an example element)

(65536, 4, 4)
[[0 0 0 0]
 [0 1 0 0]
 [1 1 0 1]
 [0 0 1 0]]

you could use numpy.meshgrid

output = np.array(np.meshgrid(*[[0,1] for _ in range(16)])).T.reshape(-1, 4,4)

as you need to get all the possible values (number of possible values = 2 ^16 = 65536)

You can loop through n from 1 to 65535, then have the binary equivalent mapped to your array that will be easiest and 100% truly unique and all possibilities included.

Eg for m1->0 : [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ] for m2->1 : [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,1] ]

     ----------------------------------------------------
     -----------------------------------------------   upto n

for m65536->65535 : [ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ]

If you need all possible arrays in random order, consider enumerating them in any arbitrary deterministic order and then shuffling them to randomize the order. If you don't want all arrays in memory, you could write a function to generate the array at a given position in the deterministic list, then shuffle the positions. Note that Fisher-Yates may not even need a dense representation of the list to shuffle... if you keep track of where the already shuffled entries end up you should have enough.

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