【问题标题】:Comparing arrays without using linq比较数组而不使用 linq
【发布时间】:2019-02-14 10:10:25
【问题描述】:

我正在制作一个彩票游戏,它要求用户输入 10 个数字,然后将其与我在数组中创建的随机数进行检查。我需要比较两者,但我不能使用 contains 方法。

我认为我需要使用 foreach 循环来比较数组,但实际上我不知道该怎么做。我一直在从我所知道的一点点拼凑起来,并想知道我是否走在正确的轨道上。

foreach 循环是比较两个数组的正确方法吗?

这是我目前的代码。

using System;

namespace lotto2
{
class Program
{
    static void Main(string[] args)
    {

        //an array named "input" to hold the users' 10 guesses
        int[] inputs = new int[10];

        //an array named "lotNum" to hold 10 random numbers
        int[] lotNums = new int[10];

        //a for loop to loop over the inputs array. each loop will ask the user for a number
        Console.WriteLine("Enter your 10 lottery numbers one at a time. The numbers must be between 1 and 25.");
        for (int i = 0; i < inputs.Length; i++)
        {
            inputs[i] = Convert.ToInt32(Console.ReadLine());
        }

        //a random number generator  
        Random ranNum = new Random();

        //loop to call the random generator 10 times and store 10 random numbers in the "lotNum" array
        for (int i = 0; i < 10; i++)
        {
            lotNums[i] = ranNum.Next(1, 26); //chooses random numbers between 1 and 25
        }

        //writes out the randomly generated lotto numbers
        Console.Write("\nThe lottery numbers are: ");
        for (int i = 0; i < 10; i++)
        {
            Console.Write("{0}  ", lotNums[i]);
        }

        //loop for checking users inputs against random generated numbers..
        //foreach loop maybe?
        foreach (var input in lotNums)
        {
        }

        //print out if there are any matches, which numbers matched

        //declared integer for the correct numbers the user guessed
        int correct;

        //end progam
        Console.WriteLine("\n\nPress any key to end the program:");
        Console.ReadKey();
    }
}

}

【问题讨论】:

  • 使用 LINQ 有什么问题?这是作业吗?
  • 是的,我正在参加在线课程,这是一项作业。
  • 这就是你不能使用 LINQ 的原因吗?
  • 考虑先对它们进行排序。另一种选择是编写自己的 Contains 方法。
  • 在这个作业中我不能使用 LINQ。

标签: c# arrays contains


【解决方案1】:

这是一个正确执行您想要的程序的程序。它甚至可以确保您没有重复的乐透号码。

void Main()
{
    const int count = 10;
    const int max = 25;

    //an array named "input" to hold the users' 10 guesses
    int[] inputs = new int[count];

    //a for loop to loop over the inputs array. each loop will ask the user for a number
    Console.WriteLine("Enter your {0} lottery numbers one at a time. The numbers must be between 1 and {1}.", count, max);
    for (int i = 0; i < inputs.Length; i++)
    {
        inputs[i] = Convert.ToInt32(Console.ReadLine());
    }

    //a random number generator  
    Random ranNum = new Random();

    //an array named "allNums" to hold all the random numbers
    int[] allNums = new int[max];
    for (int i = 0; i < allNums.Length; i++)
    {
        allNums[i] = i + 1;
    }

    //shuffle
    for (int i = 0; i < allNums.Length; i++)
    {
        int j = ranNum.Next(0, allNums.Length);
        int temporary = allNums[j];
        allNums[j] = allNums[i];
        allNums[i] = temporary;
    }

    //an array named "lotNum" to hold 10 random numbers
    int[] lotNums = new int[count];

    Array.Copy(allNums, lotNums, lotNums.Length);

    //writes out the randomly generated lotto numbers
    Console.Write("\nThe lottery numbers are: ");
    for (int i = 0; i < lotNums.Length; i++)
    {
        Console.Write("{0}  ", lotNums[i]);
    }

    int correct = 0;
    Console.Write("\nThe correct numbers are: ");
    for (int i = 0; i < lotNums.Length; i++)
    {
        for (int j = 0; j < inputs.Length; j++)
        {
            if (lotNums[i] == inputs[j])
            {
                Console.Write("{0}  ", lotNums[i]);
                correct++;
            };
        }
    }

    Console.Write("\nYou got {0} correct. ", correct);

    Console.WriteLine("\n\nPress any key to end the program:");
    Console.ReadLine();
}

【讨论】:

    【解决方案2】:

    你是在正确的方式。

    我的实现是:

    foreach (var input in inputs)
    {
        for (int i = 0; i < lotNums.Length; i++){
            if(input == lotNums[i]){
                Console.WriteLine(lotNums[i]);
            }
        }
    }
    

    这会将输入数组的每个数字与彩票数组进行比较。 我正在打印每个匹配项,但是如果找到匹配项,您可以将变量设置为 True,或者如果需要,可以将每个匹配的数字添加到数组中。

    【讨论】:

    • 这很棒。当然是这么简单的事情。我一直认为出于某种原因我需要它来开始“foreach(lotnums 中的 var 输入)”。我应该休息一下再回来。
    【解决方案3】:

    这是我尝试过的。我希望它有意义吗?

    static void LottoMethod(int[] randNums,int[] userNums)
        {
            Console.WriteLine("Guess 10 numbers");
            for(int i = 0; i <= userNums.Length-1; i++)
            {
                userNums[i] = Int32.Parse( Console.ReadLine());
            }
            Console.WriteLine("The numbers you entered: ");
            foreach(int k in userNums)
            {
                Console.Write(k+"   ");
            }
            //generate 10 numbers randomly
            Random rnds = new Random();
            for(int k = 0; k <= randNums.Length - 1; k++)
            {
                randNums[k] = rnds.Next(1, 26);
            }
            Console.WriteLine("Random Numbers");
            foreach(int i in randNums)
            {
                Console.Write(i + "   ");
            }
            int correctNums = 0;
            //Check if random numbers correspond with entered numbers
            try
            {
                for(int i = 0; i <= randNums.Length-1; i++)
                {
                    for(int j = 0; j <= userNums.Length-1; j++)
                    {
                        if (randNums[i] == userNums[j])
                        {
                            correctNums++;
                        }
                    }
                }
                Console.WriteLine($"There are {correctNums} numbers ");
            }
            catch(Exception e) {
                throw new Exception(e.ToString());
            }
        }
    

    【讨论】:

      【解决方案4】:

      你必须计算两个序列的交集。您有三个选择:

      • 双 foreach 循环。这是需要避免的,因为它的时间复杂度为 O(m*n)。 10 个项目不是问题,但我们应该制作可扩展的程序。
      • 使用散列连接。您可以为此使用 HashSet,这将是我的首选方法。但由于它固有地暗示使用Contains,所以这里不是选项。
      • 合并排序的序列。这就是去这里的方式。

      该程序是不言自明的,它产生并交叉两个随机序列。

      static Random rnd = new Random((int)DateTime.Now.Ticks);
      
      static int[] GetRandomArray(int arrSize, int minNumber, int maxNumber)
      {
          int[] tmpArr = new int[maxNumber - minNumber + 1];
          for (int i = 0; i < tmpArr.Length; ++i)
          {
              tmpArr[i] = i + minNumber; // fill with 1, 2, 3, 4,...
          }
      
          int[] ret = new int[arrSize];
          for (int i = 0; i < ret.Length; ++i)
          {
              int index = rnd.Next(tmpArr.Length - i); //choose random position
              ret[i] = tmpArr[index];
              tmpArr[index] = tmpArr[tmpArr.Length - 1 - i]; //fill last of the sequence into used position
          }
      
          return ret;
      }
      
      static IEnumerable<int> GetMatches(int[] a, int[] b)
      {
          Array.Sort(a);
          Array.Sort(b);
      
          for (int i = 0, j = 0; i < a.Length && j < b.Length;)
          {
              if (a[i] == b[j])
              {
                  yield return a[i];
                  ++i;
                  ++j;
              }
              else if (a[i] > b[j])
              {
                  ++j;
              }
              else
              {
                  ++i;
              }
          }
      }
      
      static void Main(string[] args)
      {
          var a = GetRandomArray(5, 3, 7);
          var b = GetRandomArray(10, 1, 25);
      
          Console.WriteLine("A: " + string.Join(", ", a));
          Console.WriteLine("B: " + string.Join(", ", b));
          Console.WriteLine("Matches: " + string.Join(", ", GetMatches(a, b)));
          Console.ReadKey();
      }
      

      结果是这样的:

      A: 7, 4, 6, 3, 5
      B: 17, 1, 8, 14, 11, 22, 3, 20, 4, 25
      Matches: 3, 4
      

      您可以考虑如果其中一个或两个序列包含重复项会发生什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 2011-04-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        相关资源
        最近更新 更多