How do I print on the screen the equal values of two integer vectors?

0

I did this using two for loops, but the teacher did not accept it.

I need to make the comparison using only a while loop.

EX. vetorA = {1,2,3,4,5,6,7,8} , vetorB = {3,4,7,8,9,10}

This works, but it only needs to be a loop.

public void interseccao(int[] vetorA, int[] vetorB) {
  for(int i=0; i < vetorA.length; i++){
    for(int j=0; j < vetorB.length; j++){
    if(vetorA[i] == vetorB[j]){
        int temp = vetorA[i];

        System.out.print(temp + " ");
    }
    
asked by anonymous 09.05.2018 / 01:01

1 answer

1

If you have the guarantee that the vectors are sorted you can use the following logic:

  • Begins in the first position in each of them.
  • Each step compares both values of each
  • If A is less advances only A and if B is less advances only B
  • If both are the same, show one of them and step through the two
  • Does while none of the vectors has come to an end

Implementation:

public void interseccao(int[] vetorA, int[] vetorB){
    int indiceA = 0;
    int indiceB = 0;

    while (indiceA < vetorA.length && indiceB < vetorB.length){
        if (vetorA[indiceA] == vetorB[indiceB]){
            System.out.print(vetorA[indiceA] + " ");
            indiceA++;
            indiceB++;
        }
        else if (vetorA[indiceA] < vetorB[indiceB]){
            indiceA++;
        }
        else {
            indiceB++;
        }
    }
}

What for the vectors you indicated:

int[] vetorA = {1,2,3,4,5,6,7,8};
int[] vetorB = {3,4,7,8,9,10};

Give the following output:

3 4 7 8

See it working on Ideone

    
09.05.2018 / 01:56