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

C# 将7个输入数字与7个随机数字进行比较,c#,numbers,console-application,C#,Numbers,Console Application,我是C语言新手,但我需要帮助比较我的输入值和随机数,以及我必须添加的任何函数、方法或类 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());

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

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); 
}
List lista1=新列表();

对于(int i=1;i如果您在一个列表中有输入,而在另一个列表中有随机数,您可以使用以下代码了解列表之间的共同点计数


inputs.Intersect(randoms).Count


有很多方法可以实现这一点,但一个简单的方法是在另一个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();
int[]userInputNumbers={1,2,3,4,5,6,7};
int[]numbersToCompareTo={1,9,11,12,4,6,16};
相同数字的整数计数=0;

对于(inti=0;i这就是我如何使用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();

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间控制台EApp2
{
班级计划
{
公开列出玩家{get;set;}//您的玩家
公共列表随机数{get;set;}//您的随机数生成了我的计算机
public List MatchedNumbers{get;set;}//用于存储每个玩家的匹配号码
public int NumbersRequiredCount{get;set;}=7;//取决于玩家必须猜多少个数字,初始化为7个数字
程序()
{
//实例化您的对象
Players=new List();//包含猜测数字列表的玩家列表
随机数=新列表();
MatchedNumbers=new List();//用于保存匹配的值
}
私有列表生成器自动编号(整数计数、整数最小值、整数最大值)
{
var Result=new List();//将返回结果容器
var Random=new Random();//创建随机数对象
for(int i=0;i

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

这是我的解释

    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);
    }
}
类程序
{
私有静态随机rnd=新随机();
静态void Main(字符串[]参数)
{
做
{
uint[]myRandoms=GetRandoms();
uint[]userInput=GetUserInput();
List matches=GetMatches(userInput,myRandoms);
Console.WriteLine(“您的号码”);
PrintEnumerable(用户输入);
Console.WriteLine(“彩票中奖者”);
可打印枚举(myRandoms);
Console.WriteLine(“您匹配的号码”);
可打印枚举(匹配);
int NumOfMatches=matches.Count;
如果(matches.Count>=4)
WriteLine($“你赢了!你匹配了{NumOfMatches}个数字。”);
其他的
WriteLine($“对不起,您只匹配了{NumOfMatches}个数字。”);
Console.WriteLine(“再次播放?输入Y表示是,输入N表示否”);
}而(Console.ReadLine().ToUpper()=“Y”);
}
私有静态uint[]GetRandoms()
{
uint[]newRandoms=新uint
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 };
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;
}