How to find the occurrence of equal integer values in a vector?

Asked

Viewed 337 times

8

I need to find frequency of ages in a vector. I know how to do this when the vector is small, but not when it is large. Consider the vector below:

int[] idade = {15,18,15,20,16,30,18,45,43,14,25,16,20};

For this vector, I could do a sequential search to find how many people are the same age:

for(i = 0; i < idade.length; i++){
        if(idade[i] == 14) i14++;
        if(idade[i] == 15) i15++;
        if(idade[i] == 16) i16++;
        /*if(...*/
}

Only I’m not finding a way to find the occurrence of equal ages when the vector has more than 1,000 positions. Can someone give me a hint as to how this can be done?

Thank you very much!

3 answers

5

Alternatively, the War response can be implemented as follows using only libraries that are already part of Java:

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

public class TestSorting {

public static void main(String[] args) {
    List<Integer> items = Arrays.asList(15,18,15,20,16,30,18,45,43,14,25,16,20);
    Map<Integer, Long> result =
            items.stream().collect(
                    Collectors.groupingBy(
                            Function.identity(), Collectors.counting()
                    )
            );

    Map<String, Long> finalMap = new LinkedHashMap<>();

    //Sort a map and add to finalMap
    result.entrySet().stream()
            .sorted(Map.Entry.<Integer, Long>comparingByValue()
                    .reversed()).forEachOrdered(e -> finalMap.put(String.valueOf(e.getKey()), e.getValue()));

    System.out.println(finalMap);
    //Output: {16=2, 18=2, 20=2, 15=2, 25=1, 43=1, 45=1, 14=1, 30=1}
}
}

If you only want to see the result of a member:

    System.out.println(finalMap.get("18"));
    //Output: 2
  • Hi, @Severmateus! Thank you so much for answering! I’ve already solved it! Thank you so much! _ Your solution helped me in another question!

5


My answer serves as an alternative to @Severmateus without using streams and totalizing with a normal array as if it were a HashMap. In this case it is simple to do because the range of possible values for ages is low.

So the idea starts with creating a normal array for age counting, assuming a maximum value, for the case can be 200:

int[] contagemIdades = new int[200];

Then the count is made by picking at each age, and adding at the corresponding position:

for (int i = 0; i < idades.length; ++i){
    int idade = idades[i];
    contagemIdades[idade]++;
}

After this has the built-in count vector. Each position has the amount of people of that age, which will be zero for those who did not appear.

To know which ages there is more than one person, just check whether the count is greater than or equal to 2:

for (int i = 0; i < contagemIdades.length; ++i) {
    if (contagemIdades[i] >= 2){ //apenas as idades que tem mais que uma pessoa
        System.out.printf("Existem %d pessoas com %d anos de idade\n", contagemIdades[i], i);
    }
}

See code working on Ideone

Exit:

Existem 2 pessoas com 15 anos de idade
Existem 2 pessoas com 16 anos de idade
Existem 2 pessoas com 18 anos de idade
Existem 2 pessoas com 20 anos de idade
  • Hi, @Isac! Thank you so much for answering! I’ve already solved it! Actually, your solution was very similar to mine! The difference was that I made an adaptation of the classification algorithm by counting (Counting Sort). Still, thank you very much! ^_^

4

One more alternative to solve this problem. A little simpler than the solution presented by @Severmateus.

import java.util.*;

class Main {
    public static void main(String[] args) {
        List<Integer> items = 
                 Arrays.asList(15,18,15,20,16,30,18,45,43,14,25,16,20);

        // TreeMap é inerentemente ordenado 
        Map<Integer, Integer> mapIdades = new TreeMap<>();

        // Computa os valores do map, caso seja primeira ocorrência,
        // adiciona 1, senão vai incrementando.
        items.forEach(idade -> 
                mapIdades.compute(idade, (k, v) -> v == null ? 1 : ++v));

        // Percorre valores computados
        mapIdades.forEach((idade, quantidade) -> 
                System.out.println(idade + " : " + quantidade));

    }
}

By using a Map you can also access the values directly.

mapIdades.get(15); // 2

Url to test code >>> here <<<

  • Hi! @Israelmerljak, thank you so much for answering! I got it all figured out! Thank you anyway! _ Your solution also gave me an idea for another problem! :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.