gpt4 book ai didi

c# - 检查是否已使用数组的所有值

转载 作者:行者123 更新时间:2023-11-30 13:20:25 25 4
gpt4 key购买 nike

抱歉,如果这是一个愚蠢的菜鸟问题。我正在为我的女朋友做一个非常小的项目 - 一个国家名单,她必须输入他们的首都(请注意,晦涩的国家)。由于我是一个完全的初学者,我不得不求助于使用两个数组,一个用于国家,另一个用于首都,并具有匹配的索引。这样就很容易检查正确答案,而且我不必解析任何文本文件或使用任何数据库。我正在使用随机数来让它更有趣。为了阻止程序一遍又一遍地生成相同的国家/地区,我使用了一个整数列表来跟踪已经使用了哪些索引并在列表包含前一个索引时重新生成数字。很基本的东西。令人惊讶的是,这一切都有效。

但是我遇到了一个问题。基本上,我如何检查我是否用完了国家/地区? :) 我不能简单地根据我的国家/地区数组检查列表大小,因为列表可能包含比数组更多的值,并且 if (taken.Equals(Countries.Length)) 似乎不起作用。或者我无法在代码中找到放置此检查的正确位置。

抱歉,如果这很简单,但我似乎找不到合适的解决方案。

编辑哇,多么了不起的社区。在从星巴克到我家的短短步行过程中,我得到了几十个高质量的答案,涵盖了大量的设计技术。这太棒了!谢谢大家!显然,问题已经得到解答,但如果有人有任何其他评论,我会为您发布代码。

//目前只是测试,13 个国家/地区

string[] Countries = {"Belgium", "France", "The Netherlands", "Spain", "Monaco", "Belarus", "Germany",
"Portugal", "Ukraine", "Russia", "Sweden", "Denmark", "South Africa"};
string[] Capitals = {"Brussels", "Paris", "Amsterdam", "Madrid", "Monaco", "Minsk", "Berlin",
"Lisbon", "Kiev", "Moscow", "Stockholm", "Copenhagen", "Pretoria"};
Random number = new Random();
List<int> taken = new List<int>();
int index;
int score = 0;

private int Generate()
{

while (true) {
index = number.Next(0, Countries.Length);
if (taken.Contains(index)) continue;
// THIS IS WHAT I WAS INITIALLY TRYING TO DO
if (taken.Equals(Countries.Length)) {
MessageBox.Show("Game over!");
return -1;


}
return index;
}
}


private void Form1_Load(object sender, EventArgs e)
{
index = Generate();
taken.Add(index);
label1.Text = Countries[index];
label3.Text = "0 out of " + Countries.Length.ToString();

}

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == Capitals[index].ToString()) {
label2.Text = "You win!";
index = Generate();
taken.Add(index);
label1.Text = Countries[index];
textBox1.Clear();
label3.Text = ++score + " out of " + Countries.Length.ToString();

}
else {
label2.Text = "Wrong!";
textBox1.Clear();
}
}
}
}

最佳答案

To stop the program from generating the same countries over and over again, I'm using a List of integers that keeps tracks of what indexes have already been used and regenerates the number if the list contains the previous one.

...

How do I check that I've run out of countries, basically?

您可能需要考虑一种替代方法,因为这将非常昂贵且过于复杂。

与其尝试随机添加一个国家,检查您已经添加的国家,不如制作完整的国家列表,然后 perform a shuffle (“随机排序”)在集合上。这样,您将以随机顺序一次拍摄所有国家/地区。

关于c# - 检查是否已使用数组的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com