Islands in Action

Let’s learn to tackle islands.

Check for overlaps

Islands have a little bit more to do during a game.

An island has a role to play in three actions we’ve defined in the game:

  • Positioning islands
  • Guessing coordinates
  • Checking for a forested island

Since we’ve chosen MapSets to store coordinates and hit coordinates, we have some powerful functions to help us out.

One thing we want to check when positioning islands is that they don’t overlap. We could rely solely on the front end to do this for us. However, it’s easy to check for and good to have backup validation on the back-end.

We’re representing islands as sets of coordinates. One way to determine if islands overlap is to look for any coordinates they have in common. If there are any shared coordinates between two islands, those islands overlap.

There’s a great function to test for this: MapSet.disjoint?/2. Disjointed sets share no members. If the coordinates of the two islands are disjointed, they don’t overlap.

def overlaps?(existing_island, new_island), do:
   not MapSet.disjoint?(existing_island.coordinates, new_island.coordinates)

After adding this to island.ex, the file should look like the following (additions are highlighted):

Get hands-on with 1200+ tech skills courses.