【问题标题】:How to count number of occurrences in a random array?如何计算随机数组中出现的次数?
【发布时间】:2021-03-22 06:59:24
【问题描述】:

我有一些作业在哪里。我必须编写一个简单的程序,其中生成 1-100 之间的 1000000 个随机数并将其存储在一个数组中。在程序必须打印出 25、50 和 100 的出现次数之后。我一直在尝试 for 循环,但没有运气。到现在为止我有这个:

package randomnumbers;

import java.util.Random;

public class random {
    public static void main(String[] args) {
        Random r = new Random();
        int number[] = new int[1000000];

        for (int count = 0; count < number.length; count++) {
            number[count] = 1 + r.nextInt(100);
        }
    }
}

【问题讨论】:

    标签: java arrays random counting


    【解决方案1】:
    public static void main(String[] args) {
        Random r = new Random();
        int low = 1;
        int high = 101;
        int number[] = new int[1000000];
        int count25 = 0;
        int count50 = 0;
        int count100 = 0;
    
        for (int i = 0; i < number.length; i++) {
            int num = r.nextInt(high - low) + low;
            if (num == 25) {
                count25++;
            } else if (num == 50) {
                count50++;
            } else if (num == 100) {
                count100++;
            }
            number[i] = num;
        }
        System.out.println(count25);
        System.out.println(count50);
        System.out.println(count100);
    }
    

    这里 r.nextInt(high - low) + low 在下限(包括)和上限(不包括)之间生成随机值。因此我将上限设为 101。

    有 3 个不同的计数器,如果其值与所需值(25、50 和 100)匹配,它们会加一。 循环完成后,可以打印计数器的值。

    【讨论】:

    • 嗨@Sruthi 感谢您的帮助,它工作得很好。我的号码有什么问题[count] = 1+r.nextInt(100);它不应该在1到100之间随机生成吗?我在为每个计数器执行 if 之前尝试过,但我无处可去:S
    • 它应该也可以。只是我写的通用。如果你在上面的代码中尝试int num = 1+r.nextInt(100),它的工作原理是一样的。
    【解决方案2】:

    您可以为此目的使用IntStream.count() 方法。您的代码可能如下所示:

    public static void main(String[] args) {
        // generate array of 1,000,000 elements
        int[] arr = IntStream.range(0, 1000000)
                // random value from 1 to 100
                .map(i -> (int) (1 + Math.random() * 100))
                .toArray();
    
        // test output
        System.out.println(countOf(arr, 0));   // 0
        System.out.println(countOf(arr, 1));   // 10137
        System.out.println(countOf(arr, 25));  // 10026
        System.out.println(countOf(arr, 50));  // 10103
        System.out.println(countOf(arr, 100)); // 10100
        System.out.println(countOf(null,100)); // 0
        System.out.println(countOf(arr, 101)); // 0
    }
    
    private static long countOf(int[] arr, int value) {
        if (arr == null)
            return 0;
        else
            return Arrays.stream(arr).filter(i -> i == value).count();
    }
    

    另见:
    How to find duplicate elements in array in effective way?
    How to get elements of an array that is not null?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      相关资源
      最近更新 更多