0

I have a little problem over here. I have a list of questions KlausimuList and i have to form another list Atsitiktinis witch would be a random length and would have random questions taken from KlausimuList. My method works, but the problem is - questions are duplicating. Could you please write me a code where they don't? I have an idea of making a seperate int array of indexes of questions i already added, and then each time check if that question already is in that list. If it does - genererate a new number, but i just don't know how to write the code for this thing :D. Thanks in advice. Code is in c#.

static void FormuotiAtsisiktini(List<Klausimas> KlausimuList, ref List<Klausimas> Atsitiktinis)
    {
        Random kiek = new Random();
        int kiekis = kiek.Next(1, KlausimuList.Count);
        for (int i = 0; i < kiekis; i++)
            Atsitiktinis.Add(KlausimuList[kiek.Next(1, KlausimuList.Count)]);
    }
Deividas
  • 79
  • 1
  • 9
  • 2
    Take a look at `HashSet`, it won't allow duplicates to be added: https://msdn.microsoft.com/library/bb353005(v=vs.110).aspx. Or create a copy of your original list and remove the used items from it. – Flat Eric Apr 16 '16 at 09:08

3 Answers3

1

You could use HashSet to avoid duplicates. Add method on HashSet returns false when try adding duplicate item.

static void FormuotiAtsisiktini(List<Klausimas> KlausimuList, ref List<Klausimas> Atsitiktinis)
{
     Random kiek = new Random();
    int kiekis = kiek.Next(1, KlausimuList.Count);

    HashSet<Klausimas> hashset= new HashSet<Klausimas>();

    for (int i = 0; i < kiekis;)
    {
        i+=  hashset.Add(KlausimuList[kiek.Next(1, KlausimuList.Count)])?  1:0; // returns true when successfully added.
    }

    Atsitiktinis = hashset.ToList();            
}
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

This should work. It creates a copy of the original list and removes the already taken items from it:

static List<Klausimas> FormuotiAtsisiktini(List<Klausimas> KlausimuList)
{
  Random kiek = new Random();

  List<Klausimas> source = new List<Klausimas>(KlausimuList);
  List<Klausimas> result = new List<Klausimas>();
  int kiekis = kiek.Next(1, KlausimuList.Count);
  for (int i = 0; i < kiekis; i++)
  {
    var match = source[kiek.Next(0, source.Count - 1)];
    result.Add(match);
    source.Remove(match);
  }

  return result;
}
Flat Eric
  • 7,971
  • 9
  • 36
  • 45
0

What you are describing is called sampling without replacement, and a solution to that is provided in this SO post. Furthermore, to ensure that you are actually adding duplicates to your collection, consider using a HashSet instead of a List.

Community
  • 1
  • 1
Wicher Visser
  • 1,513
  • 12
  • 21