我正在做一个必须显示文本的程序,每次用户按 Enter 键时,程序都必须从单词列表中选择随机单词并用下划线隐藏它们。
My mom loves me because I am a good boy
然后,当你按 Enter 键时,你应该会看到类似这样的内容:
My mom _____ me because _ am a good boy
如果再次按回车键,更多单词将被隐藏。那样:
My mom _____ me because _ am _ good ___
如果继续按 Enter 键,程序将隐藏更多单词,直到隐藏所有单词。当所有单词都被隐藏后,程序必须完成执行。该程序的目的是帮助人们记住文本。
我所做的是创建一个单词列表:
List<string> wordList = new List<string> {"My","mom","loves","me","because","I","am","a","good","boy"}
我使用 Random() 方法从上面的列表中随机选择一个单词:
var random = new Random();
int index = random.Next(wordList.Count);
string randomWords = scripture[index];
然后我创建了一个 for 循环来迭代单词列表,并使用 Replace() 在随机选择的位置添加下划线。最后我向用户展示这个替换的列表:
foreach (string a in wordList)
{
string newList = a.Replace(randomWords, "_");
Console.Write(newList);
Console.Write(" ");
}
我得到了这样的东西:
My _ loves because I am a good boy
当我按 Enter 时,它会再次显示带有另一个隐藏单词的文本,但它不会保留更改(我的意思是已隐藏的单词),它只是不断地无限替换单词,并且下划线的数量不等于隐藏词的字母数。请帮助我。
如果你从你的
worldList
开始,然后从该列表中构建一个随机索引列表,那么它就变成了一个问题
List<string> wordList = ["My", "mom", "loves", "me", "because", "I", "am", "a", "good", "boy"];
List<int> randomized_indices = Enumerable.Range(0, wordList.Count).OrderBy(x => Random.Shared.Next()).ToList();
然后只需从
randomized_indices
中逐步获取更多索引并用下划线替换这些单词即可。
所以从
int do_this_many = 0;
开始并称这是一个循环:
IEnumerable<string> output =
wordList
.Select((word, index) =>
randomized_indices
.Take(do_this_many)
.Contains(index)
? Regex.Replace(word, "[a-zA-Z]", "_")
: word);
在循环末尾添加
do_this_many
,直到将整个列表显示为下划线。
完整代码如下:
List<string> wordList = ["My", "mom", "loves", "me", "because", "I", "am", "a", "good", "boy"];
List<int> randomized_indices = Enumerable.Range(0, wordList.Count).OrderBy(x => Random.Shared.Next()).ToList();
int do_this_many = 0;
while (true)
{
IEnumerable<string> output =
wordList
.Select((word, index) =>
randomized_indices
.Take(do_this_many)
.Contains(index)
? Regex.Replace(word, "[a-zA-Z]", "_")
: word);
Console.WriteLine(String.Join(" ", output));
if (wordList.Count == do_this_many)
break;
do_this_many += Random.Shared.Next(1, wordList.Count - do_this_many);
}
输出如下:
My mom loves me because I am a good boy
My mom _____ __ because I am _ ____ ___
My ___ _____ __ because I am _ ____ ___
My ___ _____ __ because I __ _ ____ ___
__ ___ _____ __ because _ __ _ ____ ___
__ ___ _____ __ _______ _ __ _ ____ ___
如果我想让它更有用,我会这样做:
void Main()
{
List<string> wordList = ["My", "mom", "loves", "me", "because", "I", "am", "a", "good", "boy"];
var xs = MakeMaskLines(wordList);
foreach (var line in MakeMaskLines(wordList))
Console.WriteLine(String.Join(" ", line));
}
IEnumerable<List<string>> MakeMaskLines(List<string> words)
{
List<int> randomized_indices = Enumerable.Range(0, words.Count).OrderBy(x => Random.Shared.Next()).ToList();
int do_this_many = 0;
while (true)
{
yield return
words
.Select((word, index) =>
randomized_indices
.Take(do_this_many)
.Contains(index)
? Regex.Replace(word, "[a-zA-Z]", "_")
: word)
.ToList();
if (words.Count == do_this_many)
yield break;
do_this_many += Random.Shared.Next(1, words.Count - do_this_many);
}
}