【问题标题】:20 random numbers array from 0 to 10. How to count specific numbers in it?从0到10的20个随机数数组。如何计算其中的特定数字?
【发布时间】:2019-10-21 09:45:41
【问题描述】:

我制作了这个数组,但我在计算数字时遇到了困难。我可以通过使用“IF”10 次来做到这一点,但这对我来说似乎是错误的。也许循环“for”在这里最好用,但我不知道如何处理。

import java.util.Random;


public class zadanie2 {
    public static void main(String[] args) {
        int array[];
        array = new int[20];


        for (int i = 0; i < array.length; i++) {
            Random rd = new Random();
            array[i] = rd.nextInt(10);
            System.out.print(array[i] + ",");
        }
    }
}

【问题讨论】:

  • 您到底想达到什么目的?你想计算所有随机数的出现次数吗?如果是,请使用Map&lt;Integer, Integer&gt; 并将数字用作键,将它们的出现用作值。
  • 没错。我希望我的程序列出它们,如下所示: 1 发生 x 次; 2 发生 x 次;等等……
  • 请不要在每次迭代时创建新的Random

标签: java arrays random numbers counting


【解决方案1】:

这是为您提供的快速解决方案。检查以下代码。

    int inputArray[];
    inputArray = new int[20];
    Random rd = new Random();
    HashMap<Integer, Integer> elementCountMap = new HashMap<Integer, Integer>();
    for (int i = 0; i < inputArray.length; i++) {
        inputArray[i] = rd.nextInt(10);
    }
    for (int i : inputArray) {
        if (elementCountMap.containsKey(i)) {
            elementCountMap.put(i, elementCountMap.get(i) + 1);
        } else {
            elementCountMap.put(i, 1);
        }
    }
    System.out.println();
    System.out.println("Input Array : " + Arrays.toString(inputArray));
    System.out.println("Element Count : " + elementCountMap);

输出:

输入数组:[9, 7, 3, 0, 8, 6, 3, 3, 7, 9, 1, 2, 9, 7, 2, 6, 5, 7, 1, 5]

元素数:{0=1, 1=2, 2=2, 3=3, 5=2, 6=2, 7=4, 8=1, 9=3}

希望这个解决方案有效。

【讨论】:

  • 谢谢,但我需要一段时间才能理解这一点......就像一两天一样。你知道我在哪里可以找到一些关于 HashMap 的不错的信息吗?
  • 请不要在每次迭代时创建新的Random
  • 你可以从oracle官方网站查看更多关于HashMap的信息。链接是oracle
  • @MauricePerry 我已经更新了我的代码,所以现在新的Random 不会在每次迭代时创建。
  • 这可行,但第二个for 循环不是必需的。如果您可以在第一个循环中完成所有操作,为什么还要循环两次?数组不必完全填满即可计算数字。
【解决方案2】:

您没有存储每个随机数的出现次数,此外,您正在每次迭代中创建一个新的Random,这不应该这样做。

如果您想存储这些事件,请为此定义一个适当的数据结构,否则您将无法存储它们。我用过Map&lt;Integer, Integer&gt;,看这个例子:

public static void main(String[] args) {
    // define a data structure that holds the random numbers and their count
    Map<Integer, Integer> valueOccurrences = new TreeMap<>();
    // define a range for the random numbers (here: between 1 and 10 inclusively)
    int minRan = 1;
    int maxRan = 10;

    for (int i = 0; i < 20; i++) {
        // create a new random number
        int ranNum = ThreadLocalRandom.current().nextInt(minRan, maxRan + 1);
        // check if your data structure already contains that number as a key
        if (valueOccurrences.keySet().contains(ranNum)) {
            // if yes, then increment the currently stored count
            valueOccurrences.put(ranNum, valueOccurrences.get(ranNum) + 1);
        } else {
            // otherwise create a new entry with that number and an occurrence of 1 time
            valueOccurrences.put(ranNum, 1);
        }
    }

    // print the results
    valueOccurrences.forEach((key, value) -> {
        System.out.println(key + " occurred " + value + " times");
    });
}

作为替代方案,您可以使用Random,但对所有迭代使用一个实例:

public static void main(String[] args) {
    // define a data structure that holds the random numbers and their count
    Map<Integer, Integer> valueOccurrences = new TreeMap<>();
    // create a Random once to be used in all iteration steps
    Random random = new Random(10);

    for (int i = 0; i < 20; i++) {
        // create a new random number
        int ranNum = random.nextInt();
        // check if your data structure already contains that number as a key
        if (valueOccurrences.keySet().contains(ranNum)) {
            // if yes, then increment the currently stored count
            valueOccurrences.put(ranNum, valueOccurrences.get(ranNum) + 1);
        } else {
            // otherwise create a new entry with that number and an occurrence of 1 time
            valueOccurrences.put(ranNum, 1);
        }
    }

    // print the results
    valueOccurrences.forEach((key, value) -> {
        System.out.println(key + " occurred " + value + " times");
    });
}

请注意,这些示例不会在同一范围内创建相同的数字。

【讨论】:

    【解决方案3】:

    正如@deHaar 评论的那样,您可以使用Map 来做到这一点:

    import java.util.Map;
    import java.util.Random;
    import java.util.TreeMap;
    
    public class CountNum {
    
        public static void main(String[] args) {
            //create array and Random instance
            int[] array = new int[20];
            Random rd = new Random(System.currentTimeMillis());
    
            //create Map to count numbers occurrences
            Map<Integer, Integer> counts = new TreeMap<>();
    
            //fill array with random numbers and count the
            //occurrences in one go...
            for (int i = 0; i < array.length; i++) {
                array[i] = rd.nextInt(10);
    
                //count inserted number
                counts.put(
                    array[i],
                    counts.containsKey(array[i]) ? counts.get(array[i]) + 1 : 1
                );
            }
    
            //print count result:
            System.out.println("\n");
            for (int i : counts.keySet())
                System.out.println("The number " + i +
                        " was inserted " + counts.get(i) + " times.");
        }
    
    }
    

    打印出来

    The number 0 was inserted 1 times.
    The number 1 was inserted 1 times.
    The number 2 was inserted 3 times.
    The number 4 was inserted 1 times.
    The number 5 was inserted 1 times.
    The number 6 was inserted 5 times.
    The number 7 was inserted 3 times.
    The number 8 was inserted 3 times.
    The number 9 was inserted 2 times.
    

    【讨论】:

    • 谢谢!这个似乎更容易理解 :) 你能推荐一些好的网站来学习 HashMaps 和 TreeMap 吗?
    • @santana011 也许this 网站可以帮助你?
    【解决方案4】:

    由于您没有说明其他情况,我假设您只需要打印值:

        IntStream.range(0, 10)
              .forEach(n -> System.out.println(n + "->" + Arrays.stream(array)
                                                                .filter(i -> i == n)
                                                                .count()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多