Alister Kyle Alister Kyle - 25 days ago 9
C# Question

Eliminate duplicates from array c#

I'm making a basic Deal or No Deal game, in doing so I have to pick 10 finalists from an array, at random, without repeats.

I have my structure and arrays set out like this

public struct People
{
public string firstname;
public string lastname;
public int age;
}

class Program
{
public static People[] People1 = new People[40];
public static People[] Finalists1 = new People[10];
public static People[] Finalist1 = new People[1];


And my finalists method set out like this

Random rand = new Random();

for (int i = 0; i < Finalists1.Length; i++)
{
num = rand.Next(0, People1.Length);
Finalists1[i].lastname = People1[num].lastname;
Finalists1[i].firstname = People1[num].firstname;
Finalists1[i].age = People1[num].age;
}


How can I eliminate duplicate entries, while maintaining 10 people in the array?

Answer

Since initial array doesn't contain duplicates, you can sort it in random order and pick up 10 top items:

   Finalists1 = People1
     .OrderByDescending(item => 1)   // if people have some points, bonuses etc.
     .ThenBy(item => Guid.NewGuid()) // shuffle among peers
     .Take(10)                       // Take top 10
     .ToArray();                     // materialize as an array

If people are selected to the final are not completely random (e.g. contestant can earn points, bonuses etc.) change .OrderByDescending(item => 1), e.g.

     .OrderByDescending(item => item.Bonuses)

If you don't want to use Linq, you can just draw Peoples from urn without returning:

     private static Random random = new Random();  

     ... 

     List<People> urn = new List<People>(People1); 

     for (int i = 0; i < Finalists1.Length; ++i) {
       int index = random.Next(0, urn.Count);

       Finalists1[i] = urn[index];
       urn.RemoveAt(index);
     }