r/learncsharp • • 5d ago

How would I get randomiser to stop giving duplicate questions?

So in college we are tasked to make a short treasure hunt text game in C# using abstract classes

It works so far but one super annoying bug is that it gives repeat questions which isn't intentional. So if you got "What bird do you associate with lifting" in Canteen, sometimes when you go to for example library you will also get that question.

Randomiser class

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace TreasureHunt
{
    public class Randomiser
    {
        static Random rnd = new Random();
        private string QuestionOutput;
        private string AnswerOutput;
        public string[] Questions = ["What is there one of in every corner and two of in every room?",
        "The more there is, the less you see. What am I?" ,
        "I’m full of holes but strong as steel. What am I?",
        "You are my brother, but I am not your brother. Who am I?",
        "What bird do you associate with lifting weight?",
        "I am something people celebrate or resist. I change people’s thoughts and lives. I am obvious to some people but, to others, I am a mystery. What am I?",
        "Sometimes narrow, sometimes wide, wind or rain, I stay outside. Even if there’s heat or snow, from house to house I will still go. What am I?"];
        public string[] Answer = ["The letter O",
            "Darkness",
            "A chain",
            "Your Sister",
            "A crane",
            "Age",
            "A path"];

        public int selection = rnd.Next(0, 6);


        public string GetQuestion()
        {
            QuestionOutput = Questions[selection];
            removeQuestion(selection);
            return QuestionOutput;
        }

        public void removeQuestion(int index)
        {
            List<string> questionList = new List<string>(Questions);
            questionList.RemoveAt(index);
            Questions = questionList.ToArray();
        }

        public void removeAnswer(int index)
        {
            List<string> answerList = new List<string>(Answer);
            answerList.RemoveAt(index);
            Answer = answerList.ToArray();
        }

        public string GetAnswer()
        {
            AnswerOutput = Answer[selection];
            removeAnswer(selection);
            return AnswerOutput;
        }
    }
}

I have tried to fix this already but I haven't had much luck with it.

Other classes if it helps:

Location

using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Text;

namespace TreasureHunt
{
    abstract class Location
    {
        static Random rnd = new Random();

        
        public int selection = rnd.Next(0,4);
        public virtual string Name { get; set; }

        public Clue clue { get; protected set; }
        public Treasure treasure { get; protected set; }

        public virtual int requiredTokens { get; set; }

        public Location(string name, Clue clue, Treasure treasure, int requiredTokens)
        {
            Name = name;
            this.clue = clue;
            this.treasure = treasure;
            this.requiredTokens = requiredTokens;
            AddLocation(name, this);
        }

        public string Describe()
        {
            return $"Location: {Name}\nClue: {clue.Question}\nTreasure: {treasure.Name} - {treasure.Description}";
        }

        public void AddLocation(string name, Location location)
        {
            dictionary[name] = location;
        }

        public bool CanEnter(Player player)
        {
            if (player.CountTreasure() >= this.requiredTokens)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void enterLocation(Player player)
        {
            if (CanEnter(player))
            {
                if (player.CountTreasure() == 0)
                {
                    player.currentLocation = this;
                    return;
                }
                else if (player.CountTreasure() > 0)
                {
                    foreach (Treasure i in player.Treasures)
                    {
                        if (i.Name == treasure.Name)
                        {
                            Console.WriteLine("Nice try, but you already have this one. No one likes a cheater, buddy!");
                            player.currentLocation = null;
                            return;
                        }
                        else
                        {
                            player.currentLocation = this;
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"You need at least {requiredTokens} tokens to enter the {Name}.");
                }

            }
        }  
        public void exitLocation(Player player) 
        {
            player.currentLocation = null;
        }

        private Dictionary<string, Location> dictionary = new Dictionary<string, Location>();
    }
}

Computer Room Class(As example, subclass of the Location class)

using System;
using System.Collections.Generic;
using System.Text;

namespace TreasureHunt
{
    internal class ComputerRoom : Location
    {
        private static readonly Randomiser random = new Randomiser();
        public string Name { get; set; } = "Computer Room";
        public Clue clue { get; set; } = new Clue(random.GetQuestion(), random.GetAnswer());
        public Treasure treasure { get; set; } = new Treasure("Computer Room Token", "A token from the Computer Room.");
        public ComputerRoom() : base("Computer Room", new Clue(random.GetQuestion(), random.GetAnswer()), new Treasure("Computer Room Token", "A token from the Computer Room."), 2)
        {
        }
    }
}

Thanks

10 Upvotes

14 comments sorted by

8

u/Slypenslyde 4d ago

So, actually, this is an algorithmic problem.

Your program rolls a random number from 0-5, basically a six-sided die (d6).

If you roll the d6 and get 5, does it make sense to think you won't get another 5? What if you roll the d6 10 times? There are only 6 numbers. If you ask for 10, you MUST get a duplicate.

But that's how your program works. So you forgot to encode a requirement. You need:

  • Ask a random question.
  • If a question has been asked, do not ask that question again.
  • Stop asking questions when all have been asked.

There are two ways to do this. One is correct.

The naive thing everyone ends up writing looks like this imaginary code

var questions = [...]; // 6 questions

// Keep track of what questions we've asked
var asked = new List<int>();

while (asked.Count < questions.Length)
{
    var askIndex = Random.Shared.Next(0, questions.Length);
    if (asked.Contains(askIndex))
    {
        // This question has been asked! Try again.
        continue;
    }

    // The question has not been asked! Get the question and note
    // we've asked it.
    var question = questions[askIndex];
    asked.Add(askIndex);

    AskQuestion(question);
}

This can go very, very poorly. By the time you've asked 3 questions, you have a 50% chance of rolling an already-asked question. By the 6th question, there is only a 16% chance the roll finds the unasked question. For 6 questions this is fine, but it gets worse the more there are. I once wrote a Minesweeper game that used an algorithm like this to place mines. It took 5 minutes to generate a board because it was having to try THOUSANDS of times per mine by the last iterations on hard boards!

So that's a randomness antipattern in programming. Never, ever write code tha tries a random number then tries again if that one has already been used.

What we really need is an algorithm like:

  • Create a list of all unasked questions.
  • Choose a random item from that list and remove it.
  • Ask that question.
  • Repeat until the list is empty.

This works because by REMOVING the items we don't want, we never fail to roll the next "good" answer. So we change my code above to look like:

List<string> questions = [...]; // Using a List means we can remove items.

while (questions.Count > 0)
{
    var askIndex = Random.Shared.Next(0, questions.Count);
    var question = questions[askIndex];
    questions.RemoveAt(askIndex);

    AskQuestion(question);
}

It's easier and works more reliably. Every time a question is asked, the list gets smaller. When there are no items left in the list, you know you've asked all the questions. You can't repeat one because once asked, the question is removed from the list.

See if you can figure out how to modify your code to use this logic.

8

u/JaguarMammoth6231 4d ago

Even easier than randomize+remove is to just shuffle the list at the beginning. You can then either just iterate through the shuffled list or remove them as you pull them off the front.

4

u/Asyncrosaurus 4d ago

Shuffle into a Stack, and pop until empty.

4

u/Slypenslyde 4d ago

Then I feel compelled to sidetrack into Fisher-Yates and this is honestly one less step. "Easier" is subjective here. I think it's superior but harder to explain.

1

u/LadySonicGamer 4d ago

I tried this and now every question in the game is null

https://imgur.com/a/FuGyH27

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace TreasureHunt
{
    public class Randomiser()
    {
        
        private string QuestionOutput;
        private string AnswerOutput;
        public List<string> Questions = new List<string>
        {
            "What is there one of in every corner and two of in every room?",
            "The more there is, the less you see. What am I?",
            "I’m full of holes but strong as steel. What am I?",
            "You are my brother, but I am not your brother. Who am I?",
            "What bird do you associate with lifting weight?",
            "I am something people celebrate or resist. I change people’s thoughts and lives. I am obvious to some people but, to others, I am a mystery. What am I?",
            "Sometimes narrow, sometimes wide, wind or rain, I stay outside. Even if there’s heat or snow, from house to house I will still go. What am I?"
        };
        public List<string> AskedQuestions = new List<string>();
        public List<string> Answer = new List<string>
        {
            "The letter O",
            "Darkness",
            "A chain",
            "Your Sister",
            "A crane",
            "Age",
            "A path"
        };
        private static int maxIndex = 6;
        static Random rnd = new Random();
        public int selection = rnd.Next(0, maxIndex);
        private int current;

        private bool ReaskQuestion = false;


        public void GetQuestion()
        {
        //if (maxIndex < 0)
            //{
                //throw new InvalidOperationException("No more questions available.");
            //}
            //current = Questions.Length;

            //QuestionOutput = Questions[selection];
            while (Questions.Count() > 0)
            {
                selection = Random.Shared.Next(0, Questions.Count);
                QuestionOutput = Questions[selection];
                AnswerOutput = Answer[selection];
                Questions.RemoveAt(selection);
                
            }
            //check();
            //removeQuestion(selection);
            //DoubleCheck();
            
        }

        public string GetQuestionOutput()
        {
            return QuestionOutput;
        }

        public string GetAnswerOutput()
        {
            return AnswerOutput;
        }

        private string SavedOutput;

        private void DoubleCheck()
        {
            if (QuestionOutput != null && AnswerOutput != null)
            {
                maxIndex--;
                Console.WriteLine("Max index is now: " + maxIndex);
                if (maxIndex >= 0)
                {
                    selection = Random.Shared.Next(0, maxIndex);
                }
               //else
                //{
                    //throw new InvalidOperationException("No more questions available.");
                //}
                //throw new InvalidOperationException($"Both null: {QuestionOutput} {AnswerOutput}");
            }
        }
    }
}                                                                                                  

1

u/Slypenslyde 4d ago

Let's look at what GetQuestion() does if we convert code to English:

  • While questions remain:

    • Choose a random index.
    • Set QuestionOutput to the question with that index.
    • Set AnswerOutput to the answer with that index.
    • Remove the question with this index.

Is this the right thing? If I read your code right, and if you had commented what GetQuestion() does above it (a good practice!), it might read:

// Select a new question/answer pair. When you call this,
// QuestionOutput and AnswerOutput are set to a new
// question/answer pair, or null if all have been asked.
// This question/answer pair will be removed from future
// calls.

Is that what the code does? No! It loops through EVERY question/answer pair, removes all of the questions, and only quits when the last question/answer pair is set up. If you call it a second time, it won't do anything because it's already out of questions and, curiously, didn't remove any answers.

The code should say:

  • If any questions remain:

    • Choose a random index.
    • Set QuestionOutput to the question with that index.
    • Set AnswerOutput to the answer with that index.
    • Remove the question with this index.
    • Remove the answer with this index.

This is the appropriate code that will choose ONE question/answer pair and update the right variables. You still need to do something to tell the rest of the program when none remain.

I didn't give you code that would work if copy-pasted. I gave you code you needed to think about and integrate into your program. This is how we solve problems as developers, we usually find code that's sort of close to what we want and have to figure out how to modify it to fit our specific case. This is especially true today, with AI tools. What those spit out for me is usually only about 98% right. My job more than ever is looking for that 2% that doesn't fit and understanding what needs to be done to make it fit.

1

u/animeslut238 5d ago edited 5d ago

So each time you make a new location such as computer room are you always using a different internal class that calls new Randomiser()? If so that would be your issue as you would no longer be referencing the same array and instead are recreating the array with each location.

Edit. To be more specific you would be creating a different or new randomiser with each location.

1

u/LadySonicGamer 5d ago

How would I go about using a random from the Location itself?

1

u/Outrageous_Band9708 4d ago

when using sudo rng you have to becareful about the times its used again in the same order. you should incriment the seed value globally everytime rng is called, so that after say 5 systems use the same rng 0-6, it isn't 5 times of the same rng order, its 25 times of unique values

1

u/KiwasiGames 4d ago

Build a list. Randomise the list. Then remove each item from the list as you use it.

1

u/WystanH 2d ago

Here you've gotten a result from rnd.Next:

public int selection = rnd.Next(0, 6);

That result has been stored in selection and it is never touched again. That's the problem you currently have. Also, private string QuestionOutput; and private string AnswerOutput; aren't necessary and should be avoided. The only state in Randomiser should be that list.

The remove logic is, well, kind of absurd. Why array, list, array? You could just use a list.

Aesthetically, parallel arrays are evil. If you had a simple list of something like record QandA(string Question, string Answer); you'd have an easier time.

Hmm... While you don't offer the code for Clue, from this I'm guessing it's a lot like that QandA I just offered public Clue clue { get; set; } = new Clue(random.GetQuestion(), random.GetAnswer());. Note, again, here you've set clue; it won't change.

-2

u/FelixLeander 4d ago

School code is really a class of it's own jesus christ. Use local variables, jesus.

Personally I'd use a queue & remove each used item.

3

u/matthetherington 4d ago

Were you born knowing how to program? You just started at expert level?

Personally I'd use a queue & remove each used item.

Instead of being unwelcoming and snarky, you could have politely and helpfully explained that there's a better way to do it, like /u/Slypenslyde did.