【问题标题】:Compare two point arrays and check if there are any same items比较两个点数组并检查是否有任何相同的项目
【发布时间】:2014-03-15 00:42:30
【问题描述】:

我有一块 4x4 板。我需要创建 2 个随机的 Point 变量,然后查看这些值之前没有被随机化。

我有 2 个 Point 数组变量,分别称为 Item1Item2

假设在第一个循环之后我有 Item1[0] = (1,0) 和 Item2[0] = (3,2)
在第二个循环中,我不应该将 (1,0) 和 (3,2) 作为值
在第三个循环中,我不应该从第一个或第二个循环中获取项目

现在,对于即将到来的循环,我需要找到一种方法,以免再次选择上述项目!

我的代码:

Random rnd = new Random();
Point[] Item1 = new Point[8];
Point[] Item2 = new Point[8];
for (int x = 0; x < 8; x++)
{
//create coordinates for the first item
    Item1[x].X = rnd.Next(8);
    Item1[x].Y = rnd.Next(8);
//create coordinates for the second item
    Item2[x].X = rnd.Next(8);
    Item2[x].Y = rnd.Next(8);
}

我正在考虑创建一个List&lt;Point&gt; 并将每个点添加到列表中。但我不知道如何检查列表中的所有项目,以及如何发现这些项目不匹配。

谢谢。

附言我想创建一个记忆游戏。这就是为什么我一次需要 2 个点,这就是为什么我有独特的点很重要。

编辑:谢谢。为了将来参考,我就是这样做的。

Random rnd = new Random();
Point[] Item1 = new Point[8];
Point[] Item2 = new Point[8];
List<Point> usedPoint = new List<Point>();
for (int x = 0; x < 8; x++)
{
        do
        {
            Item1[x].X = rnd.Next(8);
            Item1[x].Y = rnd.Next(8);
        }
        while(usedPoint.Contains(new Point(Item1[x].X,Item1[x].Y))== true);
        usedPoint.Add(new Point(Item1[x].X,Item1[x].Y));
        do
        {
            Item2[x].X = rnd.Next(8);
            Item2[x].Y = rnd.Next(8);
        }
        while (usedPoint.Contains(new Point(Item2[x].X, Item2[x].Y))== true);
        usedPoint.Add(new Point(Item2[x].X, Item2[x].Y));
}

【问题讨论】:

    标签: c# arrays compare


    【解决方案1】:

    有几种方法可以解决您的问题。 如果点数变大,出于性能考虑,您应该考虑使用 Hashtable。 如果你想使用List&lt;Point&gt; list,你可以使用list.Contains(new Point(x,y))来检查这个点是否存在。

    更多关于List&lt;T&gt;.Contains的参考在这里:http://msdn.microsoft.com/en-us/library/bhkz42b3(v=vs.110).aspx

    【讨论】:

      【解决方案2】:

      你可以使用 Hashset 来提高性能 快速代码示例:您将需要类似的东西

      var random = new Random();
      var randomSet = new HashSet<int>();
      const int size = 8 * 4; // 4 because for each coordinate and each item
      for (int i = 0; i < size; i++)
      {
          var r = random.Next();
          if (!randomSet.Contains(r)) {
              randomSet.Add(r);
          }
      }
      var uniqueRandowmNumbers = randomSet.ToArray();
      int k = 0;
      for (int x = 0; x < 8; x++)
      {
      
      //create coordinates for the first item
          Item1[x].X = uniqueRandowmNumbers[k++];
          Item1[x].Y = uniqueRandowmNumbers[k++];
      //create coordinates for the second item
          Item2[x].X = uniqueRandowmNumbers[k++];
          Item2[x].Y = uniqueRandowmNumbers[k++];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        相关资源
        最近更新 更多