Created
February 2, 2016 15:01
-
-
Save oddlyfunctional/d4374b2b390803f1e9c0 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
# https://www.hackerrank.com/contests/worldcodesprint/challenges/two-pluses | |
# Enter your code here. Read input from STDIN. Print output to STDOUT | |
N, M = gets.strip.split(' ').map(&:to_i) | |
GOOD = 'G' | |
class Plus < Struct.new(:x, :y, :length); end | |
def print_grid(grid) | |
puts grid.map(&:join) | |
end | |
grid = N.times.map do | |
gets.strip.split('') | |
end | |
def longest_in_direction(grid, x, y, inc_x, inc_y) | |
new_x = x + inc_x | |
new_y = y + inc_y | |
return 0 if new_x < 0 || new_x >= N || new_y < 0 || new_y >= M | |
cell = grid[new_x][new_y] | |
return 0 unless cell == GOOD | |
return 1 + longest_in_direction(grid, new_x, new_y, inc_x, inc_y) | |
end | |
def plus_length(grid, x, y) | |
left = longest_in_direction(grid, x, y, 0, -1) | |
right = longest_in_direction(grid, x, y, 0, 1) | |
top = longest_in_direction(grid, x, y, -1, 0) | |
bottom = longest_in_direction(grid, x, y, 1, 0) | |
1 + [left, right, top, bottom].min * 2 | |
end | |
pluses_lengths = [] | |
for x in (0...N) | |
for y in (0...M) | |
cell = grid[x][y] | |
if cell == GOOD | |
pluses_lengths << Plus.new(x, y, plus_length(grid, x, y)) | |
end | |
end | |
end | |
def calculate_area(plus_length) | |
plus_length * 2 - 1 | |
end | |
def coordinates_for(plus) | |
arm = (plus.length - 1) / 2 | |
top = (1..arm).map { |i| [plus.x, plus.y - i] } | |
right = (1..arm).map { |i| [plus.x + i, plus.y] } | |
bottom = (1..arm).map { |i| [plus.x, plus.y + i] } | |
left = (1..arm).map { |i| [plus.x - i, plus.y] } | |
[plus.x, plus.y] + top + right + bottom + left | |
end | |
def intersect?(plus_a, plus_b) | |
(coordinates_for(plus_a) & coordinates_for(plus_b)).any? | |
end | |
answer = pluses_lengths | |
.combination(2) | |
.select { |plus_a, plus_b| !intersect?(plus_a, plus_b) } | |
.flat_map do |pluses| | |
pluses | |
.map { |plus| calculate_area(plus.length) } | |
.inject(1, &:*) | |
end | |
.sort | |
.last | |
answer ||= 0 | |
puts answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment