S
S
Sergey Panov2018-07-11 00:19:53
C++ / C#
Sergey Panov, 2018-07-11 00:19:53

How to take a random, unique element from an array?

Good evening friends.
There is an Array in which you need to take a random and necessarily unique element. I do it like this:

string[] Count = {"Украина","Казахстан","Беларусь", "Киргизия", "Эстония"};
int rnd = Random.Range(0, Countries.Length);

But in the end, he sometimes takes the same elements. Please tell me how to make it so that he does not take elements that he has already randomized?
Thank you!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pavlo Ponomarenko, 2018-07-11
@select8

The correct way is to sort the array randomly and then take the elements one by one from the first one. Google for the keyword Shuffle.

array.Shuffle();

foreach (var randomItem in array) {
    Console.WriteLine( randomItem );
}

P
Peter, 2018-07-11
@Morpheus_God

static void Main(string[] args)
        {
            Random rnd = new Random();

            string [] countries = { "Украина", "Казахстан", "Беларусь", "Киргизия", "Эстония","США" };

            List<string> uniqueCountry = new List<string>();
            int number;
            for (int i = 0; i < countries.Length; i++)
            {
                do
                {
                    number = rnd.Next(0, countries.Length);
                } while (uniqueCountry.Contains(countries[number]));
                uniqueCountry.Add(countries[number]);
            }

            foreach (var item in uniqueCountry)
            {
                Console.WriteLine(item);
            }   
            Console.ReadKey();
        }

A
Alexander, 2018-07-11
@alexr64

Collect the already drawn numbers in an array. Each next dropped number is compared with the numbers in the array. If this number already exists, roll the next one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question