Array.intersect solution

public Array intersect(Array other) {
var intersection = new Array(count);

for (int item : items)
  if (other.indexOf(item) >= 0)
    intersection.insert(item);

return intersection;

}

Can someone please explain the second line? (Or the logic of the entire method itself cuz I don’t get it) The method is supposed to return elements common between two Arrays, however I don’t understand why that line gives the intended result. Doesn’t that line just check to see if the index is greater than or equal to 0?

For reference below are the indexOf and insert methods.

public int IndexOf(int item)
{
for (int i = 0; i < count; i++)
{
if (items[i] == item)
return i;
}

		return -1;
	}

public void Insert(int item)
{
if (count == items.Length)
{
int[] newItems = new int[count * 2];
for (int i = 0; i < count; i++)
newItems[i] = items[i];

			items = newItems;
		}
		
		items[count++] = item;
	}

Yes. But what does that mean? If the index is greater than or equal to 0 it means that the item is contained in the array. Otherwise indexOf() would return -1.

What the method does is that it checks for every item in the array if it is also contained in the other array and if so, it adds it to the intersection array that is returned after all items have been examined.

1 Like

If the index is greater than or equal to 0 it means that the item is contained in the array. Otherwise indexOf() would return -1

I totally overlooked that, thanks much for your explanation!

That’s why it’s named intersection

How to print the common elements (intersect elements) ?
image