Reputation: 339
I am looking to generate 0's or 1's only for each array like:
int[] x = new int [10];
I would like to generate 10 numbers either 0's or 1's and should not all 0's
It's only like this:
Random binaryrand = new Random(2);
Thank you.
Upvotes: 3
Views: 5136
Reputation: 1093
This also ensures that not all are 0
Random binaryrand = new Random();
List<int> l = new List<int>();
while (l.Find(x => x == 1) != 1)
{
for (int i = 0; i < 10; i++)
{
l.Add(binaryrand.Next(0, 2));
}
}
Upvotes: 0
Reputation: 273244
Your call
Random binaryrand = new Random(2);
creates a Random generator with seed=2
, it will produce the same sequence of numbers each time you run this code. The 2
has nothing to do with the range of the generated numbers.
Use
Random binaryrand = new Random(); // auto seed
...
int x = binaryrand.Next(2);
Upvotes: 2
Reputation: 98750
You can do it with Random.Next(Int32, Int32)
method like;
int[] x = new int[10];
Random r = new Random();
while (x.Any(item => item == 1) == false)
{
for (int i = 0; i < x.Length; i++)
{
x[i] = r.Next(0, 2);
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
Example output;
0
0
0
1
1
1
0
1
1
0
Here a DEMO
.
Remember, on Random.Next(Int32, Int32)
method, lower bound is inclusive but upper bound is exclusive.
Upvotes: 3