Created
February 3, 2016 07:25
-
-
Save somzee/6e8d92b4c550b18dba7a to your computer and use it in GitHub Desktop.
HackerRank - My solution for https://www.hackerrank.com/contests/worldcodesprint/challenges/two-pluses
This file contains 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
## Solution for https://www.hackerrank.com/contests/worldcodesprint/challenges/two-pluses | |
# Read input from STDIN | |
n, m = gets.strip.split(' ').map{|x| x.to_i} | |
matrix = [] | |
n.times do |row| | |
matrix << gets.strip.split('') | |
end | |
# Calculate best area | |
def find_best_area(matrix) | |
best_area = 1 | |
all_pluses = find_all_pluses(matrix).sort.reverse | |
all_pluses.each do |plus| | |
return best_area if (plus.area ** 2) <= best_area | |
second_plus = find_second_plus(matrix, plus) | |
best_area = [best_area, (plus.area * second_plus.area)].max | |
end | |
best_area | |
end | |
# Given a matrix, find all valid pluses | |
def find_all_pluses(matrix) | |
all_pluses = [] | |
m, n = matrix.size, matrix[0].size | |
max_plus_size = [n, m].min | |
for j in 0..(m-1) do | |
for i in 0..(n-1) do | |
for plus_size in (1..max_plus_size).step(2) | |
new_plus = Plus.new(j, i, plus_size) | |
if new_plus.valid_on_matrix?(matrix) | |
all_pluses << new_plus | |
end | |
end | |
end | |
end | |
all_pluses | |
end | |
# Given a matrix and a plus, find a second valid plus | |
def find_second_plus(matrix, plus) | |
blacken!(matrix, plus) | |
second_plus = find_all_pluses(matrix).sort.last | |
whiten!(matrix,plus) | |
second_plus | |
end | |
# Change color of used cells to Bad | |
def blacken!(matrix, plus) | |
colorize(matrix, plus, 'B') | |
end | |
# Revert Blacken on matrix | |
def whiten!(matrix, plus) | |
colorize(matrix, plus, 'G') | |
end | |
# Change a color of particular element in matrix | |
def colorize(matrix, plus, color) | |
plus.coords.each do |j, i| | |
matrix[j][i] = color | |
end | |
end | |
# Define object class for Plus | |
class Plus | |
attr_reader :y, :x, :n | |
def initialize(y, x, n) | |
@x, @y, @n = x, y, n | |
end | |
def area | |
(2 * n) - 1 | |
end | |
def <=> (plus) | |
n <=> plus.n | |
end | |
def half_length | |
(n / 2).floor | |
end | |
def coords | |
coords = ((y - half_length)..(y + half_length)).map{|j| [j, x]} | |
coords += ((x - half_length)..(x + half_length)).map{|i| [y, i]} | |
end | |
def valid_on_matrix?(matrix) | |
coords.each do |j, i| | |
return false if (j < 0) || (i < 0) || matrix[j].nil? || matrix[j][i].nil? | |
return false if matrix[j][i] == 'B' | |
end | |
true | |
end | |
end | |
puts find_best_area(matrix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment