# Generate a list of randomly distributed $1$s and $0$s with fixed proportion of $1$s [duplicate]

I need to simulate a random initial state of an 1D cellular automaton, but with different 'densities' of filled cells.

Let's say the size of the list is $N$, then I need to be able to fix a number $P$ such that there are exactly $P$ $1$s and $N-P$ $0$s.

RandomInteger gives $1$s or $0$s with probability $p=1/2$, but first, I still din't work out how to correctly modify the probability so it can change from $0$ to $1$, and second, I would prefer for the number to be exact.

In other words, I have $P$ $1$s and $N-P$ $0$s and I need to randomly and uniformly distribute them inside a singe list. I'm not sure how to do that efficiently.

I suppose I could create a list of all the possible positions and use RandomSample[list,P] to fill them with $1$s. But is there a better way?

Important point! $N$ will be very large (up to 100 000).

• You want to first create a list with the correct numbers of 1s and 0s and then create a random permutation, which you can d with RandomSample. Therefore try: RandomSample[Join[ConstantArray[1, p], ConstantArray[0, n - p]]] where n is the length of the list overall and p the number of 1s. – Quantum_Oli Jan 11 '17 at 11:20
• @Quantum_Oli, thank you, that's a good idea. – Yuriy S Jan 11 '17 at 11:21

## 1 Answer

If you need precisely m zeros and n ones in random order, just put them in a list and use RandomSample to shuffle it.

m = 10;
n = 10;

RandomSample[ConstantArray[0, m]~Join~ConstantArray[1, n]]
(* {1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0} *)

• Will it work efficiently with large lists (see my edit)? – Yuriy S Jan 11 '17 at 11:26
• @YuriyS Yes. Try it. – Szabolcs Jan 11 '17 at 11:26
• Szabolcs, ok, thank you. I don't have access to Mathematica right now, that's why I was asking – Yuriy S Jan 11 '17 at 11:28