J
J
javanub2014-07-12 22:49:26
Java
javanub, 2014-07-12 22:49:26

How to count duplicate elements in an array?

For example, there is an array of the form:
char a[] = {'x', 'x', 'u', 'k', 'e', ​​'k', 'p'};
How to calculate the sum of duplicates so that it is like this:
w: 2
to: 2

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanKiLL, 2014-07-13
@javanub

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Application {

  public static void main(String[] args) {
    Map<Character, Integer> letters = new HashMap<Character, Integer>();

    ArrayList<Character> fakeArray = new ArrayList<Character>();
    fakeArray.add('a');
    fakeArray.add('a');
    fakeArray.add('a');
    fakeArray.add('b');
    fakeArray.add('b');
    fakeArray.add('c');
    fakeArray.add('c');
    fakeArray.add('c');
    fakeArray.add('w');
    fakeArray.add('w');
    fakeArray.add('w');
    fakeArray.add('w');
    fakeArray.add('g');

    for (int i = 0; i < fakeArray.size(); i++) {
      Character tempChar = fakeArray.get(i);

      if (!letters.containsKey(tempChar)) {
        letters.put(tempChar, 1);
      } else {
        letters.put(tempChar, letters.get(tempChar) + 1);
      }
    }

    for (Map.Entry<Character, Integer> entry : letters.entrySet()) {
      System.out.println("Буква = " + entry.getKey() + ", Повторений = " + entry.getValue());
    }

  }
}

And here is what is output to the console when the script has completed.
Буква = w, Повторений = 4
Буква = g, Повторений = 1
Буква = b, Повторений = 2
Буква = c, Повторений = 3
Буква = a, Повторений = 3

Probably it can be better, now Bosko does not cook sorry. But it solves the problem, dig in this direction.

T
tsarevfs, 2014-07-12
@tsarevfs

If there are few possible options for elements (for example, as in your example char 256 possible characters), then in one pass you can count the number of occurrences of each option. Else use map for that.

V
Vladlen Grachev, 2014-07-12
@gwer

Solution in the forehead.
Create an associative array (in java, map resolves them, it seems). Let's call it b. Next, loop through your entire a[]. If the element with the key a[i] is already in b, then we increment its value. If not, we add such an element to b with a value of 1.
If you need to get only duplicates, then bypass b and remove all elements that have a value of 1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question