list question

P

philip

hello, i am confused with the following code, i suppose i will get 5
numbers in the following code, but i always get 3 numbers, would u
please tell me why? thanks.


List<int> a = new List<int>();
a.Add(1);
a.Add(2);
a.Add(3);
a.Add(4);
a.Add(5);
a.Add(6);
a.Add(7);
a.Add(8);
a.Add(9);
a.Add(10);

List<int> b = new List<int>();

for(int i=0; i<5;i++){

Thread.Sleep(10);
Random randrom = new
Random(unchecked((int)DateTime.Now.Ticks));

int randomNumber = randrom.Next(0, 5);

if (!b.Contains(a[randomNumber]))
{
b.Add(a[randomNumber]);
i++;
}
else
i--;
}

foreach (int i in b)
Console.WriteLine(i);
 
G

Greg Young

You are adding twice to i every time you get a number (once in the loop and
once as part of the loop)

for (int i = 0; i < 5; i++) {

Thread.Sleep(10);
Random randrom = new
Random(unchecked((int)DateTime.Now.Ticks));

int randomNumber = randrom.Next(0, 5);

if (!b.Contains(a[randomNumber])) {
b.Add(a[randomNumber]);
i++;
} else
i--;
}

change to ..

for (int i = 0; i < 5; i++) {

Thread.Sleep(10);
Random randrom = new
Random(unchecked((int)DateTime.Now.Ticks));

int randomNumber = randrom.Next(0, 5);

if (!b.Contains(a[randomNumber])) {
b.Add(a[randomNumber]);
} else
i--;
}

or ...

int j = 0;
while (j < 5) {
Thread.Sleep(10);
Random randrom = new
Random(unchecked((int)DateTime.Now.Ticks));

int randomNumber = randrom.Next(0, 5);

if (!b.Contains(a[randomNumber])) {
b.Add(a[randomNumber]);
j++;
}
}
 
C

chanmm

Golden rule, never manipulate your loop counter inside the loop beside
increase and decrease for interacting with the loop.
So, don't play with i beside in the for statement.

chanmm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top