Skip to content

Instantly share code, notes, and snippets.

@harmaty
Last active February 27, 2017 09:52
Show Gist options
  • Save harmaty/6ae0629c257d9bf2fb606bba1dad21f8 to your computer and use it in GitHub Desktop.
Save harmaty/6ae0629c257d9bf2fb606bba1dad21f8 to your computer and use it in GitHub Desktop.
=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
require 'set'
def find_ocean(map, x, y)
return unless map[x][y] == 'W'
map[x][y] = 'O'
new_ocean_cells = [{x: x, y: y}]
loop do
water_cells = Set.new
new_ocean_cells.each do |cell|
look_for_water!(map, water_cells, cell[:x], cell[:y])
end
break if water_cells.empty?
water_cells.each do |cell| # Let's make new ocean cells
map[cell[:x]][cell[:y]] = 'O'
end
new_ocean_cells = water_cells.dup
end
end
def look_for_water!(map, water_cells, x, y)
water_cells << {x: x - 1, y: y} if x > 0 && map[x - 1] && 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'
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