How to indicate how many equal numbers exist between two vectors?

3

I have this exercise here from college:

  

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

I do not know how to develop 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 sure how to continue ...

    
asked by anonymous 18.11.2017 / 01:36

2 answers

2

Simple solution could be to compare each value of the vector with each value of vector2, if it finds, it uses a counter that increments 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++;
     }
}
    
18.11.2017 / 02:54
0

In addition, you can solve 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 making use of the following (applied to the sample code):

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

To use this, declare the vectors as below:

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

Set

     

A collection that contains no duplicate 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.

Free translation:

  

A collection that does not contain duplicate items. More formally, sets do not contain pairs of elements e1 and e2 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.

    
18.11.2017 / 04:00