比较7个输入数字和7个随机数字

时间:2019-05-26 16:27:18

标签: 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()); 
        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); 
}

5 个答案:

答案 0 :(得分:1)

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


inputs.Intersect(randoms).Count

答案 1 :(得分:0)

有许多方法可以完成此操作,但是一种简单的方法是在另一个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();

答案 2 :(得分:0)

这就是我将如何使用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();

        }
    }
}

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

答案 3 :(得分:0)

这是我的解释。

    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);
    }
}

答案 4 :(得分:0)

尝试这个经过测试的有效示例。如果运行此方法 execRandomNumber(); 您将获得此输出::

返回的数字为18
匹配的数字是18
返回的数字是15
匹配的数字是15
返回的数字是17
返回的数字是19
匹配的数字是19
返回的数字是16
匹配的数字是16
返回的数字是14
返回的数字是20
使用指令::

  android:layout_marginBottom="60dp"

声明::

using System.Collections.Generic;

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

        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));
    });
}

如果您有任何疑问,我明天会再与您联系,因为现在已经很晚了。希望这可以帮助。