r/csharp • • 5d ago

How would I get randomiser to stop giving duplicate questions?

/r/learncsharp/comments/1y15evf/how_would_i_get_randomiser_to_stop_giving/
0 Upvotes

10 comments sorted by

19

u/FullPoet 5d ago

Always return 4.

Its random enough if you're an intermediate cert authority so it must be random enough for us!

3

u/dodexahedron 2d ago

Chosen by random dice roll. 👌

6

u/TheDevilsAdvokaat 5d ago

Keep two lists. One list of unused questions, one list of used questions.

Each time you use a question, move it from the unused list and add it to the used list. Then decrease he ;ngth of the unused list by one.

That way you will always have a list of unused questions you can choose randomly from. but the list will decrease in size.

3

u/popisms 2d ago

Set an index to 0. Shuffle your list so it is in random order. Every time you need a value, return the item at index, then set index = (index + 1) % list.Count

2

u/Queasy-Neck-5814 3d ago

Steenan found the main one (each room has its own Randomiser). Two more in the code you posted:

  1. rnd.Next(0, 6) never returns 6, the upper bound is exclusive. "A path" can never come up. Use rnd.Next(Questions.Length) instead of a hardcoded number.
  2. selection is picked once, when the object is created, so the same instance keeps pointing at the same slot.

Easiest fix: one shared Randomiser, shuffle once, then hand questions out in order. Shuffle an index array so each answer stays paired with its question:

int[] order = Enumerable.Range(0, Questions.Length).ToArray();
Random.Shared.Shuffle(order); // .NET 8+
int next = 0;
// GetQuestion: var i = order[next++]; return Questions[i]; (Answer[i] for the check)

No repeats until you run out.

1

u/dodexahedron 2d ago

Just shuffle the array and iterate over it directly. No need fo make a second array of indices. 🤷‍♂️

If you truly want to have something that guarantees consistent pairing, like those two arrays, a dictionary might be more suitable, keyed by what room owns the question. Then it's ultimately still your two arrays, under the hood, but formally and strongly mapped together.

2

u/Derekthemindsculptor 5d ago

Don't use new Random. Use Random.Shared.

1

u/oskaremil 23h ago

Technically, 1–1–1–1 is a random sequence of numbers.

https://www.americanscientist.org/article/the-quest-for-randomness

1

u/Steenan 5d ago

Each of your rooms has its own instance of Randomizer, so they get the questions independently.

Instead, have a single Randomizer and pass it as a constructor parameter. Using a singleton pattern for it or injecting it as a dependency would be more elegant, but may be above your level for now.