Last active
February 27, 2017 13:54
-
-
Save harmaty/58ee722a5cebbdbf42f6d807edece8b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Given | |
1. An array of strings where "L" indicates land and "W" indicates water, | |
2. a coordinate marking a starting point in the middle of the ocean | |
The Challenge: | |
Find and mark the ocean in the map by changing appropriate W's to O's. | |
An ocean coordinate is defined to be any coordinate directly adjacent to any other ocean coordinate. | |
Example: | |
map = [ "LLLLLLLLWW", | |
"LLLLLLLWWW", | |
"WWWLLLLLWW" ] | |
coordinate: [0,9] | |
RESULT: | |
[ "LLLLLLLLOO", | |
"LLLLLLLOOO", | |
"WWWLLLLLOO" ] | |
More examples: | |
map = [ "LLWWWWLLWW", | |
"LLWLLWWWWW", | |
"WWWLLLLLWW" ] | |
coordinate: [2,8] | |
RESULT: | |
[ "LLOOOOLLOO", | |
"LLOLLOOOOO", | |
"OOOLLLLLOO" ] | |
coordinate: [1,2] | |
Same result. | |
map = [ "LWWWWLLLWW", | |
"WWLLWLLWWW", | |
"WWWWWWWWWW" ] | |
coordinate: [0,9] | |
RESULT: | |
[ "LOOOOLLLOO", | |
"OOLLOLLOOO", | |
"OOOOOOOOOO" ] | |
=end | |
# Solution with recursion | |
def find_ocean(map, x, y) | |
if map[x][y] == 'W' | |
map[x][y] = 'O' | |
adjacent_cells(map, x, y).each do |cell| | |
find_ocean map, cell[:x], cell[:y] | |
end | |
end | |
end | |
def adjacent_cells(map, x, y) | |
water_cells = [] | |
water_cells << {x: x - 1, y: y} if x > 0 && map[x - 1][y] == 'W' | |
water_cells << {x: x + 1, y: y} if map[x + 1] && map[x + 1][y] == 'W' | |
water_cells << {x: x, y: y - 1} if y > 0 && map[x][y - 1] == 'W' | |
water_cells << {x: x, y: y + 1} if map[x][y + 1] == 'W' | |
water_cells | |
end | |
map = [ "LLLLLLLLWW", | |
"LLLLLLLWWW", | |
"WWWLLLLLWW" ] | |
find_ocean(map, 0, 9) | |
map.each{|x| puts x } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment