0

I want my index to be a random number that is equal to my questions. I have a list of 33 questions which is indexed from 0-32. I have this idea that I will get random questions everytime with help of my index. This works but I still get duplicates. How do I prevent this?

 @if (questionIndex23 < 10)
        {
            <div class="app-title">
                @Questions[kuken].Category
            </div>

Here I get a random category from my list "question" with help of my index.

public void Hannes()
    {
        Random slump = new Random();
        kuken = slump.Next(1, 32);
    }

This is the method I've written to get random numbers for my index.

carlsby
  • 47
  • 6
  • create a list of integers and write a function to fill it the function would work like generate a random number and store it in the list but ignore the generated number if it exist in the list and retry – Wali Khan Jan 23 '23 at 12:10
  • 3
    Just shuffle a set of numbers representing the indexes of the questions and then consume that shuffled list from start to end. – Damien_The_Unbeliever Jan 23 '23 at 12:11
  • Random numbers *can* be duplicated in a truly random sequence, just as a dice can return 6 more than once if you throw it 6 times. What you're looking for is shuffling. – Panagiotis Kanavos Jan 23 '23 at 12:27
  • Adding to @Damien_The_Unbeliever suggestion. `Enumerable.Range(0, 32).OrderBy(_ => Random.Shared.Next()).ToList()` – Brian Parker Jan 23 '23 at 12:51

1 Answers1

3

Shuffle your questions

Random slump = new Random();
Questions = Questions.OrderBy(_ => slump.Next()).ToList();   

before displaying them

@foreach(var question in Questions)
{
    < div class="app-title">
        @question.Category
    </div>
fubo
  • 44,811
  • 17
  • 103
  • 137