在5个不同的骰子中查找2对不同的对子

问题描述 投票:-2回答:2

我有一个5个骰子的数组,我正在尝试检查它是否有两个不同的对。可以说我有(1、2、2、3)或(3、3、4、4、5)我希望它返回true。我该怎么办?

java arrays duplicates frequency dice
2个回答
0
投票

让第一个骰子成为int [] firstDice = new int [] {1,1,2,2,3};

让第二个骰子为int [] secondDice = new int [] {3,3,4,4,5};

要检查每对是否不同,只需同时遍历两个对象(前提是骰子的数量相同)。这是方法的示例:

 private boolean checkDifferentDice(int [] firstDice, int [] secondDice){
 boolean result = true;
 for (int i = 0; i < firstDice.length; i++)
 {
     if (firstDice[i] == secondDice[i])
      return false;
  }
    return result;
  }

0
投票

很简单。考虑您有一个数组,arr [5] = {1,1,2,2,3};您可以使用Set解决此问题。我正在通过使用count变量来跟踪这对货币对。

1,1,2,2,3->我要一个一个地迭代数组。当我第一次得到1时,我将其放置。第二次,检查集合,如果它包含,那么它必须是一对。

public bool findSet(int[] arr)
{ 
   HashSet<Integer> set = new HashSet<>();
   int count = 0; 
   for(int n : arr)
   {
      if(set.contains(n))
      count++;
      else
      set.add(n);
   }
   return count == 2;
 }
© www.soinside.com 2019 - 2024. All rights reserved.