1

I have been searching all over the forum and google but I think I am using the wrong key words or I do not understand the solution. What I am looking for is to create a list or array with 10 random Boolean elements where I can decide that 1 or 2 or 3 or 4 etc. elements are True. The order must be random, in the end I want a result like this e.g. (a 0.3 chance):

False
True
False
False
True
False
False
False
True
False

Thnx.

Eric S.
  • 31
  • 5
  • You can use the code below. I have not run it but should work. Please import System.Random. boolean[] randomBooleanArray(int len) { boolean[] arr = new boolean[len]; Random rand = new Random(); for(int i = 0; i < len; i++) { arr[i] = rand.NextDouble() > 0.5; } return arr; } – Egalitarian Jul 06 '17 at 18:58
  • @Egalitarian this does not ensure that `true` appears only three times. – Max Play Jul 06 '17 at 19:21

1 Answers1

5

Why not create them in a know order (true, true, true, false, ....) and then use a good algorithm to shuffle them?

An option is the good old Fisher-Yates shuffle

oerkelens
  • 5,053
  • 1
  • 22
  • 29