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

Asked

Viewed 46 times

0

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

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

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

So it works, but it needs to be only with 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 + " ");
    }
  • Post your code

  • It is guaranteed that vectors are always ordered ?

  • Yes, the vectors are ordered.

1 answer

1


If you have the assurance that the vectors are ordered you can use the following logic:

  • Start at first position in each of them.
  • At each step compare both values of each
  • If the A minor advances only in the A and whether the B minor advances only in the B
  • If both are the same show the one of them and move on the two
  • Do it while none of the vectors have 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++;
        }
    }
}

That 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 exit:

3 4 7 8

Watch it work on Ideone

  • It worked out here, thank you very much.

Browser other questions tagged

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