Here is an algorithm. It works this way.
At the beginning, all of the elements are unique for us, so we will pick an element from 0
to fruits.Length
.
After picking it, we switch the picked element with the last one.
Now we know that the last element is known for us. Let's now pick an index from 0
to fruits.Length -1
. We won't take
the last one in consideration because it is already known for us. Again, after retrieving an index, swap the element at current index with the one at fruits.Length -1
,
now we are not interested in the last 2 ones and so on.
string[] fruits = { "Apple", "Banana", "Grapes", "Orange", "Cherry", "Mango" };
Random rnd = new Random();
// This will indicate the last index for which, starting with 0, we will meet only unique elements.
int lastValidStringIndex = fruits.Length;
for (int i = 1; i <= 4; i++)
{
int rndFruits = rnd.Next(lastValidStringIndex);
Console.WriteLine(fruits[rndFruits]);
// place the current element at the end of the list
string aux = fruits[--lastValidStringIndex];
fruits[lastValidStringIndex] = fruits[rndFruits];
fruits[rndFruits] = aux;
}
Little simulation:
string[] fruits = { "Apple", "Banana", "Grapes", "Orange", "Cherry", "Mango" };
Random => "Banana"
Swap banana with Mango
string[] fruits = { "Apple", "Mango", "Grapes", "Orange", "Cherry", | "Banana" };
Random => "Orange"
Swap Orange with Cherry
string[] fruits = { "Apple", "Mango", "Grapes", "Cherry", | "Orange", "Banana" };
and so on
you got the idea. We don't check elements after |