9

I am completely stumped. I took a break for a few hours and I can't seem to figure this one out. It's upsetting!

I know that I need to check the current element in the array and see if it appears elsewhere in the array. The idea is to output the following:

The user is asked to enter 10 integers and those integers are assigned to an array (hence the "numbers" as a paremeter for the method). Let's say I enter "1, 1, 2, 3, 3, 4, 5, 6, 7, 8." The printed results should be "1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time." This printing will be done in a separate method.

Everything in my code works except for this method that I created to count the occurrences.

public static int getOccurrences(int[] numbers)
{
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
    {
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])
        {
            count++;
        }
    }

    return count;
}

I know what the issue is here. I set the current integer element in the array to the variable currentInt. The if statement counts every integer element in the array, hence the output being "[I@2503dbd3 occurs 10 times."

How do I keep track of the occurrences of each element in the array?

FrakkinShip
  • 115
  • 1
  • 2
  • 7
  • 3
    You're comparing numbers[i] with numbers[i]; it'll always be true and increment the count... – Constant Apr 14 '15 at 02:32
  • Also, there is a superfluous semicolon. – The name's Bob. MS Bob. Apr 14 '15 at 02:32
  • 3
    Do you mean "count duplicates" instead of "count occurrences"? What is the `int` you want to return from `getOccurrences()`? Show an example small array and what you expect to be returned when passed to your method – Bohemian Apr 14 '15 at 02:33
  • 2
    @Z̷͙̗̻͖̣̹͉̫̬̪̖̤͆ͤ̓ͫͭ̀̐͜͞ͅͅαлγo You're name is annoying :) – Jean-François Savard Apr 14 '15 at 02:36
  • @Bohemian The user is asked to enter 10 integers and those integers are assigned to an array (hence the "numbers" as a paremeter for the method). Let's say I enter "1, 1, 2, 3, 3, 4, 5, 6, 7, 8." The printed results should be 1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time. – FrakkinShip Apr 14 '15 at 03:04
  • @FrakkinShip Please add that to your question (click the [`edit`](http://stackoverflow.com/posts/29618205/edit) link) – Bohemian Apr 14 '15 at 03:09

16 Answers16

7
package countoccurenceofnumbers;

import java.util.Scanner;
public class CountOccurenceOfNumbers {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int [] num = new int[100]; 
        int [] count = new int[100];
        //Declare counter variable i
        //and temp variable that will
        //temporarily hold the value
        //at a certain index of num[] array
        int i,temp = 0;
        System.out.println("Enter the integers between 1 and 100: ");

        //Initialize num[] array with user input
        for(i=0; i < num.length; i++){
            num[i] = input.nextInt();
            //expected input will end when user enters zero
            if(num[i] == 0){
                break;
            }
        }//end of for loop

        //value at a given index of num array 
        //will be stored in temp variable
        //temp variable will act as an index value
        //for count array and keep track of number
        //of occurences of each number
        for(i = 0; i < num.length; i++){
                temp = num[i];
                count[temp]++;
            }//end of for looop

        for(i=1; i < count.length; i++){

            if(count[i] > 0 && count[i] == 1){
             System.out.printf("%d occurs %d time\n",i, count[i]);
             }
            else if(count[i] >=2){
                System.out.printf("%d occurs %d times\n",i, count[i]);
            }


         }//end of for loop

    }//end of main
    }//end of CountOccurrenceOfNumbers

///////////OUTPUT//////////////////////

Enter the integers between 1 and 100:
2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
BUILD SUCCESSFUL (total time: 3 minutes 23 seconds)

user1211
  • 1,507
  • 1
  • 18
  • 27
Brenda Mejia
  • 71
  • 1
  • 4
  • Hey Brenda, your code is good, but I have few question to ask, **first** what is this `count[temp]++` doing, after all my efforts, I didn't understand? **Secondly** how come count[] gets the value without even inputting something into it? **Thirdly** why did you start from 1 in the next array without starting from 0? Could you please brief me so that I can clear my concepts. Thanks :) – Alok Jan 17 '19 at 12:35
  • 1
    Hi Alok, thank you.First, the count[temp]++ is adding one at the index of temp. Which is perfect becaue if we have a user input for example 111 the num array contains those values and each time we are temporarily puting each value into the temp variable and using it as our index in the count array. Ex., temp = 1 => count[temp]++; or count[1]++; or count[1] = count[1] + 1; So since every element in the count array contains a zero we then access its contents and add a 1. When we iterate through all three 1's we then have the value 3 at count[1] so 1 was entered 3 times. – Brenda Mejia Jan 18 '19 at 20:12
  • Second, I think I answered this in the first question let me know if you are still confused. Third, Ok in the first for loop I begin with 0 because I do want to access the first element of num array to retrieve the users input, in the second one there is no need for me to start with index zero since 0 is what determines the stop of our input and we never count the frequency of zeros only the numbers 1 - 100. – Brenda Mejia Jan 18 '19 at 20:13
5

We can use java 8 Stream API to create Frequency Map

Stream.of("apple", "orange", "banana", "apple") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .forEach(System.out::println);

The downstream operation is itself a collector (Collectors.counting()) that operates on elements of type String and produces a result of type Long. The result of the collect method call is a Map.

This would produce the following output:

banana=1

orange=1

apple=2

3

@NYB You're almost right but you have to output the count value and also start it from zero on each element check.

    int count=0,currentInt=0;
    for (int i = 0; i < numbers.length; i++)
    {
    currentInt = numbers[i];
    count=0;

       for (int j = 0; j < numbers.length; j++)
           {
             if (currentInt == numbers[j])
                {
                  count++;
                 }
            }
            System.out.println(count);
      }

@loikkk I tweaked your code a bit for print out of occurrence for each element.

int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };

    Arrays.sort(a);

    int nbOccurences = 1;

    for (int i = 0, length = a.length; i < length; i++) {
        if (i < length - 1) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        } else {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //end of array
        }

        if (i < length - 1 && a[i] != a[i + 1]) {
            System.out.println(a[i] + " occurs " + nbOccurences
                    + " time(s)"); //moving to new element in array
            nbOccurences = 1;
        }

    }
Toni
  • 740
  • 2
  • 8
  • 14
2

You need two loops:

  1. For where you're starting

  2. A nested loop, to be one index in front of where you're currently at, unless you're at the end.

Is there a number you don't EVERY expect to be in your array? If so, use that value (-1 for example) as a sentinel value to overwrite your occurrences as they are counted. Then as you go through the array again for the next number to check for occurrences, you skip it if it has your sentinel value.

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
2

You can find the answer of your question here

I used Arrays.sort() method in my example:

public class MyTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int[] a = {1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1};

        Arrays.sort(a);
        int nbOccurences = 0;

        for (int i = 0, length = a.length - 1; i < length; i++) {
            if (a[i] == a[i + 1]) {
                nbOccurences++;
            }
        }

        System.out.println("Number same occurences : " + nbOccurences);
    }
}
Zayn Ali
  • 4,765
  • 1
  • 30
  • 40
1

The most efficient way is to create hashmap to save the occurrence of element while iterating the array. It will do it in 2n time complexity which is best for this problem -

HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int count;    
for(int i=0;i<arr.length;i++){
       if(hmap.get(arr[i])==null){
         hmap.put(arr[i],1);
       }else{
         count=hmap.get(arr[i]);
         count++;
         hmap.put(arr[i],count);
       }
     }
Sidharth Taneja
  • 548
  • 6
  • 7
1

Here is a full solution using Java 8 Stream to generate a frequency map. Comments to explain each step.

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

class Scratch {
    public static void main(String[] args) {
        int[] numbers = new int[]{1, 1, 2, 3, 3, 4, 5, 6, 7, 8};

        // Count up the occurrences of each number
        final Map<Integer, Long> numberToOccurrences = getFrequencyMap(numbers);

        // Print out the results
        for (Map.Entry<Integer, Long> entry : numberToOccurrences.entrySet()) {
            System.out.println(String.format("%d occurs %d times", entry.getKey(), entry.getValue()));
        }
    }

    public static Map<Integer, Long> getFrequencyMap(int[] numbers) {
        return Arrays.stream(numbers) // Use Java 8 stream
                .boxed() // convert IntStream to Stream<Integer>
                .collect(Collectors.groupingBy(
                        Function.identity(), // Key - the number
                        Collectors.counting() // Value - occurrences of the number
                ));
    }
}

Running it prints the output

1 occurs 2 times
2 occurs 1 times
3 occurs 2 times
4 occurs 1 times
5 occurs 1 times
6 occurs 1 times
7 occurs 1 times
8 occurs 1 times
James Mudd
  • 1,816
  • 1
  • 20
  • 25
0

You need to sort the order of your numbers in the array. You can use a 'sort()' method, which will organize your numbers from smallest to biggest.

You also need two loops, one to compare against the other. Or in my solution's case, I used a 'while statement' and then a 'for loop'.

I dunno if my method of solving your problem is what you are looking for. Maybe there is a shorter and/or better way to solve this. This is just the way I thought of it. Good luck!

public static int getOccurrences(int[] numbers){

    Array.sort (numbers); //sorts your array in order (i,e; 2, 9, 4, 8... becomes, 2, 4, 8, 9)

    int count = 0;
    int start = 0; 
    int move = 0;

        while(start < numbers.length){
            for (int j = 0; j < numbers.length; j++){
                int currentInt = numbers[start];;
                if (currentInt == numbers[j])
                {
                    count++;
                    move++;
                }
            }
                if(count == 1){
                    return ("Number : " + numbers[start] + " occurs " + count + " time ");
            }   else {
                    return ("Number : " + numbers[start] + " occurs " + count + " times ");
            }
                count = 0;
                start = start + move;
                move = 0;
        }
}
user1211
  • 1,507
  • 1
  • 18
  • 27
Kitoliwa
  • 61
  • 1
  • 7
0

Just copy and execute it, it will give you the no of occurrence of integers in array.

public class noOfOccurence{  

public static void main(String[] args){

    int a[] = {1,9,4,5,6,7,5,6,7,3,2,5,7,9,0,4,3,5,1,4,6,0,2,3,1,4,3,8};

    HashSet<Integer> al = new HashSet<Integer>();

   //Store the array in set as set will store unique elemnets
    for(int i=0;i<a.length;i++){
        //int count =0; 
        al.add(a[i]);
    }
    //printing the set
    System.out.println("al "+al);


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

            if(set==a[j]){
                count++;
            }
        }
        System.out.println(set+" occurs "+count+" times");
    }
  }
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
0
import java.util.Scanner;

public class array2 {
    public static void main (String[]args) {
        Scanner input = new Scanner (System.in);
        int [] number = new int [101];
        int c;

        do {

            System.out.println("Enter the integers from 1-100");
            c = input.nextInt();
            number[c]++;

        }while (c != 0);
        for(int i = 0; i < number.length ; i++) {
            if (number[i] !=0) {
                if (number[i] == 1)
                    System.out.println(i + " occurs " + number[i] + " time");
                else
                    System.out.println(i + " occurs " + number[i] + " times "); 

            }
        }
    }
}
mypetlion
  • 2,415
  • 5
  • 18
  • 22
0
// i use List<Integer> to solve the problem. it's not a concise way

public static List<List<Integer>> occurence(int[] cards) {

  // first, we create a ArrayList to store the distinct number and its corresponding count value
  //it takes time
  List<List<Integer>> element = new ArrayList<>();

  int tmp=cards[0],  count=0;
  int total = cards.length;

  for(int i=0; i < total; i++) {

    if(i == total -1) {
      if( cards[i] == tmp) {

          List<Integer> l = new ArrayList<>();
          l.add(tmp);
          l.add(count+1);
          element.add(l);
          break;
      }else {
        List<Integer> l = new ArrayList<>();
        l.add(tmp);
        l.add(count);
        element.add(l);

        l = new ArrayList<>();
        l.add(cards[i]);
        l.add(1);
        element.add(l);
        break;
      }

    }

    if(cards[i] == tmp) {
      count++;        
    }else { 
      List<Integer> l = new ArrayList<>();
      l.add(tmp);
      l.add(count);
      element.add(l);

      tmp = cards[i];
      count = 1;  //we already have 1 occurence of cards[i]. i.e. tmp       
    }
  }

  return element;
}
Yusef Maali
  • 2,201
  • 2
  • 23
  • 29
Mike Xue
  • 31
  • 4
0
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 // This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
public class fileopen {
    public static void main(String[] args) {

        String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        List<String> list = new ArrayList<String>();

        String[] country = null;
        Map<String, Integer> hm = new HashMap<String, Integer>();
        try {

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                country = line.split(cvsSplitBy);

                list.add(country[2]);

                System.out.println(country[1]);
            }
            for (String i : list) {
                Integer j = hm.get(i);
                hm.put(i, (j == null) ? 1 : j + 1);
            }
            // displaying the occurrence of elements in the arraylist
            for (Map.Entry<String, Integer> val : hm.entrySet()) {
                if(val.getKey().equals("Error Message")){
                    System.out.println(val.getKey());
                    continue;
                }
                System.out.println(val.getKey() + " " + val.getValue());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 1
    Please add some description so that the OP can learn from your answer and help him understand what went wrong. – VPK Dec 10 '19 at 06:38
0

Please try this 3 way may help you

Way1: with 2 loop

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;       
        for(int i=0;i<arr.length;i++){
            for(int j=0;j<arr.length;j++){
                if(arr[i] == arr[j]){  
                    if(j<i){
                        break;
                    }                   
                    count++;
                }               
            } 
            if(count > 0){  
                System.out.println("occurence of "+arr[i]+"  "+(count));                 
                count = 0;
            }
         }         
    }
}

Way2: with 1 loop

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0;  
        int temp = 0;
        for(int i=0;i<arr.length;i++){              
            if(arr[count] == arr[i]){  
                 if(i<count){
                    if(count<arr.length-1)
                       count++;
                     i=0;
                        //  break;
                  }else{
                    temp++;  
                  }
            } 
                               
           if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
           if(i == arr.length-1 && count<i){
               if(count<arr.length-1)
                  count++;
               i=0;                 
            }        
          }   
    }
}

Way3: with switch statement

public class Main {
    public static void main(String args[]) {
        int arr[] = {1,2,2,3,4,1,1,5,5,1};
        // Arrays.sort(arr);
        int count = 0; 
        int temp = 0;
        for(int i=0;i<arr.length;i++){ 
              switch(0){
                  case -1:
                  default:
                    if(arr[count] == arr[i]){  
                      if(i<count){
                        if(count<arr.length-1)
                          count++;
                         i=0;
                         break;
                    }else{
                        temp++;  
                    }
                  } 
              }                  
           
            if(i == arr.length-1 && temp > 0){
                System.out.println("occurence of "+arr[count]+"  "+(temp)+". "+i);                 
                temp = 0;   
            }
                  
            if(i == arr.length-1 && count<i){
                if(count<arr.length-1)
                  count++;
                i=0;                 
            }        
         }   
    }
}
gpuser
  • 1,143
  • 1
  • 9
  • 6
0
import java.util.*;

public class noOfOccurence{  

public static void main(String[] args){
    
    int[] arr  = new int[200];
    Scanner sc = new Scanner(System.in);
    
    int n = sc.nextInt();
    Set<Integer> s = new HashSet<Integer>();
    
    for(int i = 0; i < n ; i++)
    {
        arr[i] = sc.nextInt();
        
        s.add(arr[i]);
        
    }
    
    for(int result : s)
    {
        int count = 0;
        for(int j=0; j<n; j++)
        {
            if(result == arr[j])
            {
                count++;
            }
        }
        
        if(count == 1)
        {
            System.out.println(result + " Present in " + count + " time");
        }
        else
        {
       System.out.println(result + " Present in " + count + " times");
        }
    }
    
    
    
    
}
}
Oussama ZAGHDOUD
  • 1,767
  • 5
  • 15
0

Solution with nested loop, the result of the above code will be a map with element as key and occurrence count as value, there's an array that store if that index was visited or not to avoid for the next iteration.

static Map<Integer, Integer> getDuplicatedCount(int[] data) {

    Map<Integer, Integer> result = new HashMap<>();
    int[] visited = new int[data.length];
    for (int i = 0; i < data.length; i++) {
        for (int j = i + 1; j < data.length; j++) {
            if (data[i] == data[j]) {
                visited[j] =-1;
                if (visited[i] !=-1) {
                    if (result.get(data[i]) == null) {
                        result.put(data[i], 2);
                    } else {
                        result.put(data[i], result.get(data[i]) + 1);
                    }
                }

            }
        }
    }
    return result;
}
-2
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};  

//Array fr will store frequencies of element  
int [] fr = new int [arr.length];  
int visited = -1;  
for(int i = 0; i < arr.length; i++){  
    int count = 1;  
    for(int j = i+1; j < arr.length; j++){  
        if(arr[i] == arr[j]){  
            count++;  
            //To avoid counting same element again  
            fr[j] = visited;  
        }  
    }  
    if(fr[i] != visited)  
        fr[i] = count;  
}
janw
  • 8,758
  • 11
  • 40
  • 62