Amol Nalge
Amol Nalge

Reputation: 11

Check no of occurance of all digits in array using single for Loop or use Any Collection

Integer a[]={10,20,30,10,10,20,50,60,50,50};

for(int i=0;i<a.length;i++)
{

             int count=0;
            for(int j=0;j<a.length;j++)
            {

                if(a[i]==a[j])
                {
                    count++;

                }
            }
            System.out.println(a[i]+" occurs times ="+count);
            count=0;
}

Upvotes: 1

Views: 90

Answers (4)

Ebraheem Alrabeea
Ebraheem Alrabeea

Reputation: 2250

I think you want the output with no duplicate message with one loop

consider using Set to remove duplicate number

Look at this code:

Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        System.out.println("Number of Occurence of " + integer + ": " +
                   Collections.frequency(Arrays.asList(a), integer));
    }
}

Update With Regards To Comment

This is the same code without using Collections class:

Integer a[] = { 10, 20, 30, 10, 10, 20, 50, 60, 50, 50 };
Set<Integer> noDuplicateInt = new HashSet<>();
Map<Integer, Integer> numOccurenceMap = new HashMap<>();
for (Integer integer : a) {
    if (noDuplicateInt.add(integer)) {
        numOccurenceMap.put(integer, 1);
    } else {
        numOccurenceMap.replace(integer, numOccurenceMap.get(integer) + 1);
    }
}
System.out.println(numOccurenceMap); 

Upvotes: 0

Nonika
Nonika

Reputation: 2560

Integer a[] = {10, 20, 30, 10, 10, 20, 50, 60, 50, 50};
Map<Integer, Integer> integerIntegerMap =
        Stream.of(a).collect(Collectors.groupingBy(o -> o))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey, o -> o.getValue().size()));
System.out.println(integerIntegerMap);

Output:

{50=3, 20=2, 10=3, 60=1, 30=1}

Upvotes: 3

Lino
Lino

Reputation: 19926

You can use a Map<Integer, Integer>:

Map<Integer, Integer> map = new HashMap<>();

for(int i : a){
    map.compute(i, ( key, value ) -> value == null ? 1 : value + 1);
}

Which results in map containing the items in the array a as Keys and the amount of occurances of that item as the Value

Upvotes: 1

Cat
Cat

Reputation: 1363

Consider the following piece of code:

 public class HelloWorld{

    public int static[] apps = new int[10]; // stores the nr. of appearences of each digit

    public static int calcNr(int a) // calculates for each element in the array
    {
        while(a>0)
        {
            apps[a%10]++;
            a = a/10;
        }
    }

    public static calcArray(int [] v)
    {
        for(int i = 0; i<v.length; i++)
            calcNr(v[i]);
    }

     public static void main(String []args){
        //...
        int n; // nr of elements
        int [] array = new array[n];
        calcArray(array);
     }
}

Upvotes: 0

Related Questions