這裏是一個簡短而完整的程序,它不會因爲你需要(我使用一個控制檯應用程序,而非形式):
private static void Main(string[] args)
{
string dialogResult = "";
bool[] alreadyGuessed = new bool[10];
int guesses = 0;
Random newNumberGenerator = new Random();
do
{
int number = newNumberGenerator.Next(0, 10);
if (!alreadyGuessed[number])
{
guesses++;
alreadyGuessed[number] = true;
Console.WriteLine("Are you thinking of the number " + number.ToString() + "?")
dialogResult = Console.ReadLine();
}
}
while (dialogResult.ToUpper() != "Y" && guesses < 10);
if (dialogResult.ToUpper() == "Y")
{
Console.WriteLine("I guessed the number!");
}
else
{
Console.WriteLine("No numbers left!");
}
Console.ReadLine();
}
在原始程序中的邏輯似乎有些倒退;目前還不清楚是用戶還是計算機做猜測。這個程序假設你正在考慮一個介於0和9之間的數字(包括這個數字),並讓計算機試圖猜測它,但你顯然可以根據自己的需要進行調整。我也省略了任何驗證邏輯。
編輯:正如Tarec正確指出的那樣,這不會擴展到非常大的數量集合。要做到這一點你需要一個合適的洗牌算法是這樣的:
public static void Shuffle(int[] array)
{
var random = new Random();
for (int i = array.Length; i > 1; i--)
{
int j = random.Next(i);
int temp = array[j];
array[j] = array[i - 1];
array[i - 1] = temp;
}
}
然後,你可以將程序更改此:
private static void Main(string[] args)
{
string dialogResult = "";
int size = 10;
int[] array = Enumerable.Range(0, size).ToArray();
Shuffle(array);
for (int i = 0; i < size; i++)
{
int number = array[i];
Console.WriteLine("Are you thinking of the number " + number.ToString() + "?");
dialogResult = Console.ReadLine();
if (dialogResult.ToUpper() == "Y")
{
break;
}
}
if (dialogResult.ToUpper() == "Y")
{
Console.WriteLine("I guessed the number!");
}
else
{
Console.WriteLine("No numbers left!");
}
Console.ReadLine();
}
現在你可以改變「大小」,以任何你喜歡的和程序將正常工作。不過,這對於原始海報的需求可能是過度的。
這不是最佳解決方案。它是非確定性的,因爲你正在運行你的循環,直到所有的隨機數被使用,這是錯誤的。在每次迭代中最後一位數字的一些近似變體中,您將有1/10的機會實際擊中正確的數字。想象一下,你用1000或1000萬的數字而不是10來運行它,你註定要失敗。 – Tarec
當然。但我們並不是針對1,000或1,000,000個數字運行,而是針對10個運行。這不是一個可擴展的解決方案,但它確實解決了OP的具體問題。 (另外,更改爲一百萬個數字(自動檢查)在大約三秒鐘內運行,所以我認爲'註定失敗'有點誇張!) –
非常感謝。這工作得很好! – MrDevo