-2

Okay I know there are few posts like this but I need to use only loops (for,do,while) and if, else to fill array with random but unique numbers so how shall i edit this code

        int[] x = new int[10];
        Random r = new Random();

        int i;
        for (i = 0; i < x.Length; i++) {

            x[i] = r.Next(10);
            Console.WriteLine("x[{0}] = {1}", i, x[i]);
        }
user6055525
  • 3
  • 1
  • 5
  • 2
    "Random but unique" - that's not random :) – CompuChip Mar 13 '16 at 17:35
  • so I mean that when i randomize it wont repeat i used r.next(10) just because it was easier to spot whether it repeats or not so it shiuld use each number only once – user6055525 Mar 13 '16 at 17:37
  • 1
    If you have a target array length of 10, and only want numbers up to 10, then you actually just want to shuffle the array `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`. And that’s explained in the linked question. – poke Mar 13 '16 at 17:41
  • no i need to increase random generated numbers limit from 0,100 i used 10 on code now just so it was easier that it doesn't repeat – user6055525 Mar 13 '16 at 17:43
  • 1
    Is 100 the final upper limit? Then create an array from 0…100, shuffle that, and take the first 10 numbers. That’s still more efficient than generating random numbers while checking all the time whether you already had that one or not. – poke Mar 13 '16 at 17:50
  • You could come up with something more interesting for daily question... (previous http://stackoverflow.com/questions/35965056/fill-array-with-random-but-unique-numbers-in-c-sharp link for 10K+) - you really should put at least some effort in doing your homework/entertainment project. – Alexei Levenkov Mar 13 '16 at 17:55

2 Answers2

1

You could check if the newly generated number already exists in the array, if not then add it to the array, if yes then generate a new one.

For examle:

class Program
{
    static void Main(string[] args)
    {
        int[] x = new int[10];
        Random r = new Random();

        int i;
        for (i = 0; i < x.Length; i++)
        {
            var next = 0;                
            while (true)
            {
                next = r.Next(10);
                if (!Contains(x, next)) break;                    
            }

            x[i] = next;
            Console.WriteLine("x[{0}] = {1}", i, x[i]);
        }

        Console.ReadLine();
    }

    static bool Contains(int[] array, int value)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == value) return true;
        }
        return false;
    }
}
Andrey Polyakov
  • 203
  • 1
  • 9
Bogoljub
  • 73
  • 6
0

Without checking that generated number is already presented in array you can't to solve this task.

So you must generate new number and before inserting it into array check for uniq.

Andrey Polyakov
  • 203
  • 1
  • 9