Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my lottery program wrong ? or am I so unlucky?

Tags:

c#

I made a lottery program : http://yadi.sk/d/bBKefn9g4OC7s

Here is the whole source code : http://yadi.sk/d/rnQMfrry4O8cu

Random rnd = new Random();
int[] loto;
loto = new int[7];

for (int f = 1; f <= 6; f++) {
    loto[f] = rnd.Next(1, 50); // Generating random number between 1-49

    for (int h = 1; h < f; h++) {
        if (loto[f] == loto[h]) { // Check with other numbers for the case of duplicate
            loto[f] = rnd.Next(1, 50); // If there is a duplicate create that number again
        }
    }
}

This section I'm generating random 6 different numbers between 1-49

Also I'm wondering in this example, are nested loops increase the spontaneity ?

I'm getting 3-4 max, this program wrong or am I so unlucky ?

( note that : that's my first program )

For all guys trying to help me : I'm really beginner on programming(c# yesterday | c++ 3 weeks i guess), and if you guys clarify what you mean in codes it'll be great. And please not give me extreme hard coding examples( I don't wanna quit c# )

like image 527
1342 Avatar asked Jan 14 '23 13:01

1342


1 Answers

Your method looks unsafe, as get value from Random again in the inner loop does not guarantee that it will return unduplicated value. For low value as 1-49, you can use simple random-picking algorithm like this

    var numbers = new List<int>();
    for (int i = 1; i <= 49; i++) {
        numbers.Add(i);
    }
    Random r = new Random();
    var loto = new int[6];
    for (int f = 0; f < 6; f++) {
        int idx = r.Next(0, numbers.Count);
        loto[f] = numbers[idx];
        numbers.RemoveAt(idx);
    }

Note that this is far from optimal solution in terms of performance, but if you will run it only once in a few seconds or more so it should be fine.

like image 104
tia Avatar answered Jan 16 '23 03:01

tia