java - 100 次循环完成后,如何获得比较总数?

标签 java arrays loops unique

程序运行 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 的构造函数而不是使用无参数构造函数(它依赖于 compareToInteger 方法)。

这样您将实现 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/

相关文章:

python - Google App Engine 使用数组将模板变量传递到 View 中

c - 返回带有字符串输入的字符串数组

javascript - 如何在for循环中返回一个减一的数组中的一个值

java - 如何将 bundle 数据从一个 fragment 获取到另一个 fragment ?

java - 字符串的整数值

java - NetBeans 和类似 Eclipse 的 "run configurations"

ios - 在 DetailViewController 中的索引路径之间转换? swift

r - 通过删除一些 NA 单元来压缩数据帧?

java - 更改嵌套循环中静态类变量的值

java - MPAndroidchart 库中的折线图 x 轴值重绘