Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created July 1, 2013 17:07
Show Gist options
  • Save ackintosh/5902661 to your computer and use it in GitHub Desktop.
Save ackintosh/5902661 to your computer and use it in GitHub Desktop.
class NumberOfIsland
(class << self; self; end;).class_eval do
def output(input)
input.split("\n\n").inject([]) { |result, line| result << run(line) }.join("\n")
end
def run(input, x = 0, y = 0, checked = [], count = 0)
ary = convert_to_array(input)
ary.size.times do
row = []
ary[0].size.times do
row << nil
end
checked << row
end
count(ary, checked)
end
def count(ary, checked, x = 0, y = 0, count = 0)
return count if ary.size <= x
if ary[x][y] == 1 && checked[x][y] == nil
count += 1
checked = check(ary, checked, x, y) if ary[x][y] == 1
end
if ary[x].size >= y + 1
return count(ary, checked, x, y + 1, count)
else
return count(ary, checked, x + 1, 0, count)
end
end
def check(ary, checked, x, y)
return checked if checked[x][y] == true
return checked if ary[x][y] == 0
checked[x][y] = true if ary[x][y] == 1
checked = check(ary, checked, x + 1, y) if ary.size > x + 1
checked = check(ary, checked, x, y + 1) if ary[x].size > y + 1
checked = check(ary, checked, x - 1, y) if 0 <= x - 1
checked = check(ary, checked, x, y - 1) if 0 <= y - 1
return checked
end
def convert_to_array(input)
input.each_line.inject([]) { |res, line| res << line.chomp.split('').map { |n| n.to_i } }
end
end
end
input = <<"EOS"
111100001111
111000001111
110000001111
100000001111
000100010000
000000111000
000001111100
100011111110
110001111100
111000111000
111100010000
000000000000
010001111100
110010000010
010010000001
010000000001
010000000110
010000111000
010000000100
010000000010
010000000001
010010000001
010010000010
111001111100
000000000000
111111111111
100010100001
100010100001
100010100001
100010100001
100100100101
101000011101
100000000001
100000000001
111111111111
100000000001
EOS
if __FILE__ == $0
p NumberOfIsland.output(input)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment