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)]);
    }
1

3 Answers 3

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();            
}
Sign up to request clarification or add additional context in comments.

2 Comments

Worked perfectly. Thanks! :)
It would probably make more sense to return a list and not have the ref parameter. I know that's how the OP was but it's still a little weird
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;
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.