【问题标题】:How can I get the total number of comparisons after the 100 loops have finished?100 次循环完成后,如何获得比较总数?
【发布时间】:2016-09-26 18:15:55
【问题描述】:

程序运行 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
        }
    }
}

【问题讨论】:

  • 您的代码并没有完全按照您的想法进行。它实际上从 140 个不同的范围(仅 0,然后是 0 或 1,然后是 0、1 或 2,等等)生成 14000 个整数。
  • 是的,它在技术上是 14000 个整数,但它是 100 组数组,每个数组中有 140 个元素(减去重复项)。我运行它时很好。
  • System.out.println(14000);

标签: java arrays loops unique


【解决方案1】:

计算比较次数的一种方法是将自己的Comparator&lt;Integer&gt; 实例传递给TreeSet 的构造函数,而不是使用无参数构造函数(它依赖于IntegercompareTo 方法)。

这样您将自己实现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);          
    }
}

正如大卫华莱士所说,您可能应该修复您的随机数生成逻辑:

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
}

【讨论】:

  • 啊,谢谢!我一定会修复我的随机数生成器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 2021-12-01
  • 1970-01-01
  • 2017-07-04
  • 2015-03-02
  • 2021-10-17
  • 2013-08-17
相关资源
最近更新 更多