程序运行 100 次并打印出 140 个整数中的唯一元素。
由于需要比较两个整数来判断它们是否唯一,如何打印比较的总数?
这是我的代码:
public class UniqueElements {
public static void main(String[] args) {
// TODO code application logic here
Set<Integer> uniqueKeys = new TreeSet<Integer>();
//Use TreeSet to eliminate all duplicate integers in the array
for (int runs = 0; runs <= 100; runs++) { //program loops 100 times
for (int numbers = 1; numbers <= 140; numbers++) {
//add 140 integers in array
Random rand = new Random(System.nanoTime());
uniqueKeys.add(rand.nextInt(numbers));
//make the 140 integers random, including duplicates
}
System.out.print("Unique Elements: " + uniqueKeys + "\n");
//print unique elements in array
}
}
}
最佳答案
统计比较次数的一种方法是通过自己的Comparator<Integer>
实例到 TreeSet
的构造函数而不是使用无参数构造函数(它依赖于 compareTo
的 Integer
方法)。
这样您将实现 compare
方法自己,并且将能够在调用时增加计数。
例如:
...
Set<Integer> uniqueKeys = new TreeSet<Integer>(new MyComparator());
...
public class MyComparator implements Comparator<Integer>
{
private int count = 0;
public int compare (Integer a, Integer b)
{
count++;
System.out.println(count); // instead of printing the counter each time
// this method is called, you can print it
// once at the end of your program
return Integer.compare(a,b);
}
}
正如 David Wallace 所提到的,您可能应该修复您的随机数生成逻辑:
Random rand = new Random(); // use a single Random generator
int max = ...;
for (int numbers = 1; numbers <= 140; numbers++) {
uniqueKeys.add(rand.nextInt(max)); // use the same range for all
// the random generated numbers
}
关于java - 100 次循环完成后,如何获得比较总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39709661/