计算数组中数字的出现次数 [英] counting occurrence of numbers in array

查看:48
本文介绍了计算数组中数字的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一段时间了.我试过调试,但找不到解决方案.我正在尝试计算数字的出现次数.所以我的问题是当我打印输出时它是

I am stack for a while . I tried debugging but I couldn't figure out the solution. I am trying to count the occurrence of numbers. So my problem is that when I print the output it is

3 occurs 1 times
1 occurs 1 times
0 occurs 1 times
2 occurs 1 times
1 occurs 2 times
3 occurs 2 times
2 occurs 2 times
0 occurs 2 times
10 occurs 1 times
4 occurs 1 times

代替

1 occurs 2 times
0 occurs 2 times
2 occurs 2 times
3 occurs 2 time
10 occurs 1 times
4 occurs 1 times 

所以如果数字出现超过 1 次,它应该只说一次,而不是出现次数多.干杯这是代码

so if the number has more than 1 occurrence it should say it only once not as many times as there is occurrences. Cheers Here is the code

import java.util.*;

public class CountingOccuranceOfNumbers
{

    public static void main(String[] args) 
    {
        countNumbers();
    }

    public static void countNumbers()
    {
        Scanner input = new Scanner(System.in);
        Random generator = new Random();
        int[] list = new int[11];
        int[] counts = new int[150];
        int counter = 0;
        int number = 1;


        while(counter <= 10)
        {
                number = generator.nextInt(11);
                list[counter] = number;
                counter++;
        }   
        for(int i=0; i<list.length - 1; i++)
        {
            counts[list[i]]++;
//          System.out.print(list[i] + " ");

            System.out.println(list[i] +" occurs " +  counts[list[i]] + " times");
        }

    }

}

推荐答案

另一个选项是 guava 的 Multiset classes,它将为您跟踪计数:

Another option is guava's Multiset classes, which will track the count for you:

int values[] = ...;
Multiset<Integer> ms = HashMultiset.create();
ms.addAll(Ints.asList(list));

int count0 = ms.count(Integer.valueOf(0));
int count1 = ms.count(Integer.valueOf(1));

这里,Multiset、HashMultiset 和 Ints 都是番石榴类.

Here, Multiset, HashMultiset and Ints are all guava classes.

请注意,Multiset 通过使用 Map 和计数器来跟踪计数器几乎可以完成上面提到的那些.它只是从您那里抽象出来,使您的代码更简单.

Note that Multiset does pretty much what someone mentioned above by using a Map and counter to track the counters. It's just abstracted away from you to make your code simpler.

这篇关于计算数组中数字的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆