[英]Comparing elements in my array to find pairs, but can't figure out what to do when it finds two pairs
I am trying to compare elements in a single array to pull out any pairs, three of a kind, four of a kind, or five of a kind... I can't seem to wrap my head around how to do so. 我正在尝试比较单个数组中的元素,以抽取出任意对,三对,四对或五对……我似乎无法全力以赴。 I also have to print out the number in which is in a pair, three of a kind, etc... This is what I have so far. 我还必须打印出一对中的数字,三个中的数字,等等。。。 Any clues or ideas? 有任何线索或想法吗?
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;
}
}
The key is to somehow keep track of which elements in the array have already been counted. 关键在于以某种方式跟踪数组中哪些元素已被计数。 The simplest method is to use a boolean
array of the same length, and set it to true when you find a matching element. 最简单的方法是使用相同长度的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 %ds\n", count, d1[i]);
}
}
}
When called with input [5, 5, 3, 3, 3]
this prints 当使用输入[5, 5, 3, 3, 3]
5、5、3、3、3]调用时[5, 5, 3, 3, 3]
将输出
2 5s
3 3s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.