将 7 个输入数字与 7 个随机数进行比较



我是C sharp的新手,但我需要帮助来比较我的输入值和随机数,我必须添加的任何函数,方法或类。

List<int> lista1 = new List<int>(); 
for (int i = 1; i <= 7; i++) 
{ 
try { 
Console.Write("First Number {0}: ", i); 
int x = Convert.ToInt16(Console.ReadLine()); 
lista1.Add(x); 
} catch (Exception ex){ 
Console.WriteLine("The input number is incorret! It has to be whole number"); 
Console.WriteLine("Error: {0}", ex.Message); 
i--; 
} 
Console.WriteLine("Random Numbers are: "); 
InitArray(); 
Console.WriteLine(item); 
}

如果输入在列表中,而随机数在另一个列表中,则可以使用以下代码来了解列表之间的公共计数。


inputs.Intersect(randoms).Count

这是我的解释。

class Program
{
private static Random rnd = new Random();
static void Main(string[] args)
{
do
{
uint[] myRandoms = GetRandoms();
uint[] userInput = GetUserInput();
List<uint> matches = GetMatches(userInput, myRandoms);
Console.WriteLine("Your Numbers");
PrintEnumerable(userInput);
Console.WriteLine("The Lottery Winners");
PrintEnumerable(myRandoms);
Console.WriteLine("Numbers You Matched");
PrintEnumerable(matches);
int NumOfMatches = matches.Count;
if (matches.Count >= 4)
Console.WriteLine($"You win! You matched {NumOfMatches} numbers.");
else
Console.WriteLine($"Sorry, you only matched {NumOfMatches} numbers.");
Console.WriteLine("Play again? Enter Y for yes and N for no.");
} while (Console.ReadLine().ToUpper() == "Y");
}
private static uint[] GetRandoms()
{
uint[] newRandoms = new uint[7];
int index = 0;
while (index < 7)
{
//.Next(int, int) limits the return to a non-negative random integer 
//that is equal to or greater than the first int and less than the second the int.
//Said another way, it is inclusive of the first int and
//exclusive of the second int.
uint r = (uint)rnd.Next(1, 40);
if (!newRandoms.Contains(r)) //prevent duplicates
{
newRandoms[index] = r;
index++;
}
}
return newRandoms.OrderBy(x => x).ToArray();
}
private static uint[] GetUserInput()
{
uint[] inputs = new uint[7];
int i = 0;
while (i < 7)
{
Console.WriteLine("Enter a whole number between 1 and 39 inclusive. No duplicates, please.");
//Note: input <= 39 would cause an error if the first part of the
// if failed and we used & instead of && (And instead of AndAlso in vb.net).
//The second part of the if never executes if the first part fails
//when && is used.                                                             //prevents duplicates
if (uint.TryParse(Console.ReadLine(), out uint input) && input <= 39 && input >0 && !inputs.Contains(input))
{
inputs[i] = input;
i++; //Note: i is not incremented unless we have a successful entry
}
else
Console.WriteLine("Try again.");
}
return inputs.OrderBy(x => x).ToArray();
}
//I used a List<T> here because we don't know how many elements we will have.
private static List<uint> GetMatches(uint[] input, uint[] rands)
{
List<uint> matches = new List<uint>();
int i;
for (i=0; i<7; i++)
{
if(rands.Contains(input[i]))
matches.Add(input[i]);
}
//Or skip the for loop and do as Sunny Pelletier answered
//matches = input.Intersect(rands).ToList();
return matches.OrderBy(x=>x).ToList();
}
//You are able to send both List<T> and arrays to this method because they both implement IEnumerable
private static void PrintEnumerable(IEnumerable<uint> ToPrint)
{
foreach (uint item in ToPrint)
Console.WriteLine(item);
}
}

有很多方法可以实现这一点,但一个简单的方法是在另一个 for 循环中使用 for 循环。 即

int[] userInputNumbers = {1,2,3,4,5,6,7};
int[] numbersToCompareTo = {1,9,11,12,4,6,16};
int countOfNumbersThatAreTheSame = 0;
for(int i=0; i<userInputNumbers.Length; i++)
{
for(int j=0; j<numbersToCompareTo.Length; j++)
{
if(userInputNumbers[i] == numbersToCompareTo[j])
{
countOfNumbersThatAreTheSame++;
}
}
}
Console.Write(countOfNumbersThatAreTheSame);
Console.Read();

这就是我使用 CSharp 干净利落地接近它的方式。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public List<List<int>> Players { get; set; } //Your Players
public List<int> RandomNumbers { get; set; } //Your Random numbers enerated my Computer
public List<List<int>> MatchedNumbers { get; set; } //to store Matched Numbers for each player
public int NumbersRequiredCount { get; set; } = 7; //Depends on how many numbers the players must guess, initialize to 7 numbers
Program()
{
//Instantiate your objects
Players = new List<List<int>>(); //List of Players with their list of guessed numbers
RandomNumbers = new List<int>(); 
MatchedNumbers = new List<List<int>>(); //To hold Matched Values
}
private List<int> GenerateAutoNumbers(int Count, int Min, int Max)
{
var Result = new List<int>(); //Result Container - will be returned
var Random = new Random(); //Create Random Number Object
for(int i = 0; i < Count; i++)
{
//Generate your random number and save
Result.Add(Random.Next(Min, Max));
}
//Return "Count" Numbers of Random Numbers generated
return Result;
}
public List<int> EvaluateMatches(List<int> Inputs, List<int> Bases)
{
var result = new List<int>();
//Inplement a counter to check each value that was inputted
for(int i = 0; i <  Inputs.Count; i++)
{
for (int r = 0; r < Bases.Count; r++)
{
//Check if the current input equals the current Random Number at the given index
if(Inputs[i] == Bases[r])
{
//If matched. Add the matched number to the matched list
result.Add(Inputs[i]);
}
}
}
//At this point, all matched numbers are organized in result object
return result; //return result object
}
static void Main(string[] args)
{
Program App = new Program();
//Players must input numbers - Assuming they must guess between 1 - 100
//It can be as many players
//Player 1
App.Players.Add(new List<int> { 5, 47, 33, 47, 36, 89, 33 });
//Player 2
App.Players.Add(new List<int> { 1, 17, 38, 43, 34, 91, 24 });
//Player 3
App.Players.Add(new List<int> { 6, 74, 39, 58, 52, 21, 9 });
//At this point the inputs are all in for the 3 players
//Now generate your RandomNumbers
App.RandomNumbers = App.GenerateAutoNumbers(App.NumbersRequiredCount, 1, 100);
//Now you need to evaluate the guessed numbers
//For each Player
for(int p = 0; p < App.Players.Count; p++)
{
//Create the list for each user to hold the matched numbers
App.MatchedNumbers.Add(App.EvaluateMatches(App.Players[p], App.RandomNumbers));
}
//Now all Players numbers are evaluated, all you need is to print the results
Console.WriteLine("Results has been retrieved");
Console.Write("Generated Numbers are: ");
foreach(int i in App.RandomNumbers)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Following Matches were Found: ");
for(int p = 0; p < App.Players.Count; p++)
{
Console.Write($"Player {p + 1} has {App.MatchedNumbers[p].Count} Matches: ");
foreach(int i in App.MatchedNumbers[p])
{
Console.Write(i + "  ");
}
Console.WriteLine();
}
Console.Write("n");
Console.WriteLine("Press any Key to Exit!");
Console.ReadKey();
}
}
}

它将打印屏幕上匹配的数字。

试试这个经过测试和工作的例子。如果你运行此方法execRandomNumber();你会得到这个输出 ::

返回的数字是 18
匹配的数字是 18
返回的数字是 15 匹配的数字是 15
返回的数字是 17

返回的数字是 19 匹配的数字是 19

返回的数字是 16 匹配的数字是 16
返回的数字是 14

返回的数字是 20
使用指令 ::

using System.Collections.Generic;

声明::

public static List<int> lista1 = new List<int>();
public static List<int> returnedRandomList = new List<int>();
public static int[] myArrNums = new[] { 12, 25, 15, 16, 18, 19 };
public static int[] myRandArr = new[] { 14, 15, 16, 17, 18, 19, 20 };

方法 1 适用于需要生成随机数的情况::

private void execRandomNumber()
{
//==============Don't have the numbers but need to generate them?==============
returnedRandomList = Gen(returnedRandomList, null);
returnedRandomList.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers returned are ", num));
if (numIsMatch(num) == true)
{
lista1.Add(num);
Console.WriteLine(string.Concat("The numbers matching are ", num));
}
});
//==============Generator will return list of random numbers, then we compared them==============
}

您的号码生成器 ::

//==============Your number generator==============
private List<int> Gen(List<int> randGenerator, Random ranNum)
{
ranNum = new Random();
var rn = 0;
returnedRandomList.Clear();
do
{
if (randGenerator.Count == 7)
break;
rn = ranNum.Next(14, 21);
if (!(randGenerator.Contains(rn)) && randGenerator.Count <= 7)
randGenerator.Add(rn);
}
while (randGenerator.Count <= 7);
return randGenerator;
}

对于方法二,假设您已经生成数字并将其存储在数字列表或数组中,您可以执行以下操作::

private void runArgs()
{
//==============Already have the numbers? Loop through them and compare==============
foreach (int i in myRandArr)
{
if (numIsMatch(i) == true)
{
lista1.Add(i);
}
}
lista1.ForEach(delegate (int num)
{
Console.WriteLine(string.Concat("The numbers that match are ", num));
});
}

为了比较你的数字,看看它们是否匹配,你可以做这样的事情::

//==============Check is numbers are a match==============
private bool numIsMatch(int inValue)
{
foreach (int ii in myArrNums)
{
if (ii.Equals(inValue))
return true;
else
continue;
}
return false;
}

如果你有任何问题,我明天会回复你,因为现在已经很晚了。希望这有帮助。

最新更新