-
Notifications
You must be signed in to change notification settings - Fork 0
/
map_size_test.rb
41 lines (37 loc) · 1.28 KB
/
map_size_test.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
M = 'land'
o = 'water'
world = [[o,o,o,o,o,o,o,o,o,o,o],
[o,o,o,o,M,M,o,o,o,M,o],
[o,o,o,M,M,M,M,o,o,M,o],
[o,o,M,M,M,o,o,M,o,M,o],
[o,M,M,M,o,o,o,o,o,o,o],
[o,o,o,o,M,M,M,o,M,M,o],
[o,M,o,M,M,o,o,o,o,o,o],
[o,M,M,o,o,M,M,o,o,o,o],
[o,M,M,M,M,M,o,o,o,M,o],
[o,o,M,M,o,M,o,o,M,M,o],
[o,o,o,o,M,M,o,o,o,o,o]]
def continent_size world, x, y
if y > world.length-1 || x > world[y].length-1 || y < 0 || x < 0 # indices are out of bounds
return 0
elsif world[y][x] != 'land'
# either it's water or we already counted it
# but either way, we don't want to count it now.
return 0
end
# So first we count this tile...
size = 1
world[y][x] = 'counted land'
# ...then we count all of the neighboring eight tiles
# (and, of course, their neighbors by way of the recursion).
size = size + continent_size(world, x-1, y)
size = size + continent_size(world, x-1, y-1)
size = size + continent_size(world, x-1, y+1)
size = size + continent_size(world, x, y-1)
size = size + continent_size(world, x, y+1)
size = size + continent_size(world, x+1, y)
size = size + continent_size(world, x+1, y-1)
size = size + continent_size(world, x+1, y+1)
size
end
puts continent_size(world, 5, 1)