Zestyyy Zestyyy - 6 months ago 7
Ruby Question

How do I account for an array that doesn't exist?

So the code works fine if I'm trying to find the size of the land in the middle, but it fails when calculating the size of the small land in the corner. How do I return

0
if it starts checking for land outside of the given arrays?

M = 'land'
o = 'water'

world = [[o,o,o,o,o,o],
[o,M,M,M,o,o],
[o,o,M,M,o,o],
[o,o,o,o,o,M]]

def continent_size world, x, y
if world[x][y] != 'land'
return 0
end

size = 1
world[x][y] = 'counted land'

size = size + continent_size(world, x-1, y-1)
size = size + continent_size(world, x , y-1)
size = size + continent_size(world, x+1, y-1)
size = size + continent_size(world, x-1, y )
size = size + continent_size(world, x+1, y )
size = size + continent_size(world, x-1, y+1)
size = size + continent_size(world, x , y+1)
size = size + continent_size(world, x+1, y+1)

size
end

puts continent_size(world, 3, 5)

Answer

How about some guard clauses at the top of your method like:

# make sure we don't attempt to index into an array at less than zero
return 0 if x < 0
return 0 if y < 0

# make sure there is a value in the requested slot
return 0 unless world[x]
return 0 unless world[x][y]