How to indicate how many equal numbers there are between two vectors?

Asked

Viewed 433 times

3

I’ve got this exercise here from college:

Write a java program that takes two size vectors different and then indicates how many equal numbers there are between these two vectors.

I’m not able to develop the logic, for now the code is just reading the arrays:

    package vetores2;
   import java.util.Scanner;

    public class ex02 {

  public static void main(String[] args) {

    Scanner entrada = new Scanner(System.in);

    int[] vetor  = new int[10];
    int[] vetor2= new int[9];
    int totalIgual = 0;

    System.out.println(" Insira os valores do primeiro vetor");
    for(int i = 0; i < vetor.length; i++) {
        vetor[i] = entrada.nextInt();
    }
    System.out.println(" Insira os valores do segundo vetor");
    for(int i = 0; i < vetor2.length; i++) {
        vetor2[i] = entrada.nextInt();
    }

From there I’m not able to continue...

  • Vector only or you can use Collection within the method?

  • Technically, since I’m a beginner I shouldn’t use, but using or not valid. good that I learn with more practicality.

2 answers

2


Simple solution could be to compare each value of the vector with each value of the vector 2, if found, uses a counter that increases if it finds an equal.

int contador = 0;
for(int i = 0; i < vetor.length; i++) {
     for(int j = 0; j < vetor2.length; j++) {
          if(vetor[i] == vetor2[j])
              contador++;
     }
}
  • I had done so, but I realized that, for example, if both vectors have the value 2, but in vector 1 the index is [2] and in vector 2 the index is [4], it will not be added in total

  • @Yan Luis regardless of the Indice, each vector 1 value is compared with all vector 2 values .

  • Wow, so I misinterpreted the code. Thank you very much, Jorge!

1

For complementary, it can be solved using Collection with the following method:

public Integer[] encontrarInterseccao(Integer[] vetor1, Integer[] vetor2) {
  Set<Integer> conjunto1 = new HashSet<>(Arrays.asList(vetor1));
  Set<Integer> conjunto2 = new HashSet<>(Arrays.asList(vetor2));

  conjunto1.retainAll(conjunto2);

  return conjunto1.toArray(new Integer[conjunto1.size()]);
}

And using it as follows (applied to the example code):

System.out.println(Arrays.toString(encontrarInterseccao(vetor, vetor2)));

To use this way declare the vectors as below:

Integer[] vetor = new Integer[10];
Integer[] vetor2 = new Integer[9];

Set

A Collection that contains no Uplicate Elements. More formally, sets contain no pair of Elements E1 and E2 such that E1.equals(E2), and at Most one null element. As implied by its name, this interface models the Mathematical set abstraction.

In free translation:

A collection that does not contain duplicate items. More formally, sets do not contain pairs of E1 and E2 elements in case of E1.equals(E2). As the name suggests, this interface is an abstraction of the mathematical model "set".


You can also use a solution with Java 8 based in this answer of Stack Overflow:

public int[] encontrarInterseccao(int[] vetor1, int[] vetor2) {
  return Arrays.stream(vetor1)
          .filter(x -> Arrays.stream(vetor2).anyMatch(y -> y == x))
          .toArray();
}

But keep in mind that in this solution, if there are repeated elements, they will also appear several times in the result.

  • I must say that despite being a fan of streams, I didn’t like your alternative using streams. At work we often use a strategy called (internally as a joke) "slay dragons", or "kill Langos" when the problem consists of small collections. Basically, it consists in transforming one of the collections into an "assossiative memory" structure so that in normally O(1), I can get the proper priority. Normally we use to moisturize entities having only their codes and a list of identities, but in this case it would be to verify whether it belongs to the set or not

Browser other questions tagged

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