0

我正在做一个问答游戏。我需要打乱数组,以便问题、选项和答案数组不会按顺序出现。

这是三个数组。

public string[] EasyQuestions = 
{
    "What is the capital of Australia?",
    "Who was Steve Jobs?",
    "What number Apollo took Neil Armstrong to the moon?",
    "Which metal is heavier, silver or gold?",
    "What country has the largest population?"
};

public string[] EasyOptions = 
{
    "Brisbane |Canberra |Adelaide |Australian Capital Territory",
    "CEO of Microsoft |Co-founder of Apple |Creator of IBM |Australian Politician",
    "10|11|12|1",
    "Silver|Gold|Gold|Silver",
    "'Murica|China|India|Australia"
};

public string[] EasyAnswers = 
{
    "Canberra",
    "Apple",
    "11",
    "Gold",
    "China"
};

我希望所有数组都被相同地洗牌,这样我就不会因为不同的选项和不同的问题得到错误的答案?

4

3 回答 3

4

正如我在评论中建议的那样,如果您将所有内容组合在一起,那么您无需担心保持同步:

public class Question {

    private List<string> answers;

    public Question(string text, IEnumerable<string> answers, int answer) {
        this.Text = text;
        this.Answer = answer;

        this.answers = new List<string>(answers);
    }

    public string Text {
        get;
        private set;
    }

    public int Answer {
        get;
        private set;
    }

    public IEnumerable<string> Answers {
        get {
            return this.answers;
        }
    }

    public string GetAnswer() {
        return this.answers[this.Answer];
    }
}
于 2013-09-20T02:53:41.473 回答
3

使用Fisher-Yates shuffle。它一次性对元素进行洗牌。

Random rnd = new Random();

for (int i = 0; i < EasyQuestions.Length - 1; i++) {
    int j = rnd.Next(i, EasyQuestions.Length);

    string temp = EasyQuestions[j];
    EasyQuestions[j] = EasyQuestions[i];
    EasyQuestions[i] = temp;

    temp = EasyOptions[j];
    EasyOptions[j] = EasyOptions[i];
    EasyOptions[i] = temp;

    temp = EasyAnswers[j];
    EasyAnswers[j] = EasyAnswers[i];
    EasyAnswers[i] = temp;
}
于 2013-09-20T02:52:18.090 回答
0

不要对数组本身进行洗牌。相反,打乱一个包含 0 到 4 的整数列表。由于这似乎是家庭作业,我会让您弄清楚如何使用该打乱列表。

于 2013-09-20T02:53:29.003 回答