Nested loops: looking for duplicates in arrays

A and B are arrays of integers. Construct code to output all of the values that are in both A and B.

With questions like this, imagine you had to do it manually. Imagine you have two long lists of numbers on paper. How would you find all the values that occur in both lists?

You would probably look at the first number from list A and then scan all the way down list B to see if it’s there. If it was you’d make a note of it. Then you would get the next number from list A and do the same thing.

A computer algorithm will do exactly the same thing.

In pseudocode this is:

loop I from 0 to A.length - 1
  loop J from 0 to B.length - 1
    if A[I] = B[J] then
      output A[I]
    end if
  end loop
end loop

In Java it is:

for (int i = 0; i < a.length; i++) {
  for (int j = 0; j < b.length; j++) {
    if (a[i] == b[j]) {
      System.out.println(a[i]);
    }
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s