1
$\begingroup$

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).

$\endgroup$

marked as duplicate by Szabolcs, Quantum_Oli, corey979, Mr.Wizard list-manipulation Jan 11 '17 at 12:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ 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. $\endgroup$ – Quantum_Oli Jan 11 '17 at 11:20
  • $\begingroup$ @Quantum_Oli, thank you, that's a good idea. $\endgroup$ – Yuriy S Jan 11 '17 at 11:21
1
$\begingroup$

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} *)
$\endgroup$
  • $\begingroup$ Will it work efficiently with large lists (see my edit)? $\endgroup$ – Yuriy S Jan 11 '17 at 11:26
  • $\begingroup$ @YuriyS Yes. Try it. $\endgroup$ – Szabolcs Jan 11 '17 at 11:26
  • $\begingroup$ Szabolcs, ok, thank you. I don't have access to Mathematica right now, that's why I was asking $\endgroup$ – Yuriy S Jan 11 '17 at 11:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.