比较数组中的元素以查找对,但找不到两对时该怎么做



我正在尝试比较单个数组中的元素以提取任何对,三种,四种或五种......我似乎无法弄清楚如何做到这一点。我还必须打印出一对、三种等中的数字......这就是我目前所拥有的。有什么线索或想法吗?

import java.util.Arrays;
public class DieGame3 {
public static void main(String[] args) {
Die die1 = new Die(6);
System.out.println("Welcome to the pairing game!");
System.out.print("The 5 rolled dice: ");
int[] numbers = new int[5];
for(int i = 0; i < numbers.length; i++) {
die1.roll();
numbers[i] = die1.getValue();
}
System.out.println(Arrays.toString(numbers));
findPairs(numbers);
}
public static int[] findPairs(int[] d1) {
int count = 0;
for (int i = 0; i < d1.length; i++) {
for (int k = i + 1; k < d1.length; k++) {
if (d1[i] == d1[k]) {
count++;
}
}
}
if(count == 1)
System.out.println("You've got " + count + " pair.");
else
System.out.println("You've got " + count + " of a kind.");
return d1;
}
}

关键是以某种方式跟踪数组中的哪些元素已经被计算在内。最简单的方法是使用相同长度的boolean数组,并在找到匹配元素时将其设置为 true。

public static void findPairs(int[] d1) {  
boolean[] seen = new boolean[d1.length];
for (int i = 0; i < d1.length-1; i++) {
if(!seen[i])
{
int count = 1;
for (int k = i + 1; k < d1.length; k++) {
if (d1[i] == d1[k]) {
seen[k] = true;
count++;
}
}
if(count > 1)
System.out.printf("%d %dsn", count, d1[i]);
}
}
}

当使用输入调用时[5, 5, 3, 3, 3]这将打印

2 5s
3 3s

最新更新