Hany Moh. Hany Moh. - 23 days ago 8
Java Question

find repeated elements and count of their

i want to give an array of integers, determine the number of repeated integers and their counts.

this is the full code after edit

// Enter array size:
Scanner input = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = input.nextInt();
int[] crr_array = new int[size];
int[] new_array= new int[size];
int[] times = new int[size];

// Enter array elements:
System.out.println("Enter array elements: ");
for (int i = 0; i < crr_array.length; i++) {
crr_array[i] = input.nextInt();
times[i] = 1;
}

//search

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

for (int i = j; i < crr_array.length; i++) {

if (crr_array[j] == crr_array[i] && j != i) {

new_array[i] = crr_array[i];
times[i]++;
}


}

}



//Printing output
for (int i = 0; i < new_array.length; i++) {
System.out.println("\t" + crr_array[i] + "\t" + new_array[i] + "\t" + times[i]);

}


I want to get output like that

count of elements //3
element: count times //2 times
element: count times //3times
element: count times //2 times


i hope to get output like

There are 3 repeated numbers:
22: 2 times
4: 3 times
1: 2 times


i'm sorry about bad english

Answer

This kind of problems can be easy solved by dictionaries (HashMap in Java).

  // The solution itself 
  HashMap<Integer, Integer> repetitions = new HashMap<Integer, Integer>();

  for (int i = 0; i < crr_array.length; ++i) {
      int item = crr_array[i];

      if (repetitions.containsKey(item))
          repetitions.put(item, repetitions.get(item) + 1);
      else
          repetitions.put(item, 1);
  }

  // Now let's print the repetitions out
  StringBuilder sb = new StringBuilder();

  int overAllCount = 0;

  for (Map.Entry<Integer, Integer> e : repetitions.entrySet()) {
      if (e.getValue() > 1) {
          overAllCount += 1;

          sb.append("\n");
          sb.append(e.getKey());
          sb.append(": ");
          sb.append(e.getValue());
          sb.append(" times");
      }
  }

  if (overAllCount > 0) {
      sb.insert(0, " repeated numbers:");
      sb.insert(0, overAllCount);
      sb.insert(0, "There are ");
  }

  System.out.print(sb.toString());