-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]);
        }
6
  • 2
    "Random but unique" - that's not random :) Commented Mar 13, 2016 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 Commented Mar 13, 2016 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. Commented Mar 13, 2016 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 Commented Mar 13, 2016 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. Commented Mar 13, 2016 at 17:50

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

can you please tell me how can i do it ?
This algorithm crashes Unity for some reason.
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.

1 Comment

how can i check if its unique ? what will the code be

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.