Fast Random Permutation of Binary Array

384 views Asked by At

For my project, I wish to quickly generate random permutations of a binary array of fixed length and a given number of 1s and 0s. Given these random permutations, I wish to add them elementwise.

I am currently using numpy's ndarray object, which is convenient for adding elementwise. My current code is as follows:

    # n is the length of the array. I want to run this across a range of 
    # n=100 to n=1000.
    row = np.zeros(n)
    # m_list is a given list of integers. I am iterating over many possible
    # combinations of possible values for m in m_list. For example, m_list
    # could equal [5, 100, 201], for n = 500.
    for m in m_list: 
        row += np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))

My question is, is there any faster way to do this? According to timeit, 1000000 calls of "np.random.permutation(np.concatenate([np.ones(m), np.zeros(n - m)]))" takes 49.6 seconds. For my program's purposes, I'd like to decrease this by an order of magnitude. Can anyone suggest a faster way to do this?

Thank you!

1

There are 1 answers

0
Severin Pappadeux On

For me version with array allocation outside the loop was faster but not much - 8% or so, using cProfile

row = np.zeros(n, dtype=np.float64)
wrk = np.zeros(n, dtype=np.float64)

for m in m_list:

    wrk[0:m] = 1.0
    wrk[m:n] = 0.0

    row += np.random.permutation(wrk)

You might try to shuffle(wrk) in-place instead of returning another array from permutation, but for me difference was negligible