Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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 );
}
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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question