lundi 21 janvier 2019

How can I fill array with unique random numbers with for-loop&if-statement?

I'm trying to fill one dimensional array with random BUT unique numbers (No single number should be same). As I guess I have a logical error in second for loop, but can't get it right.

P.S I'm not looking for a more "complex" solution - all I know at is this time is while,for,if. P.P.S I know that it's a really beginner's problem and feel sorry for this kind of question.

        int[] x = new int[10];

        for (int i = 0; i < x.Length; i++)
        {
            x[i] = r.Next(9);

            for (int j = 0; j <i; j++)
            {
                if (x[i] == x[j]) break;

            }
        }
        for (int i = 0; i < x.Length; i++)
        {
            Console.WriteLine(x[i);
        }




Aucun commentaire:

Enregistrer un commentaire