Last active
June 1, 2016 18:02
-
-
Save jagdeepsingh/2e51106976148feddadb0c6c224fb186 to your computer and use it in GitHub Desktop.
Ruby practices
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
#!/bin/ruby | |
class CavityFinder | |
def initialize(grid) | |
@grid = grid | |
end | |
def cavities | |
cavities = [] | |
i = 1 | |
while i < size - 1 | |
j = 1 | |
while j < size - 1 | |
cavities << [i, j] if is_cavity?(i, j) | |
j += 1 | |
end | |
i += 1 | |
end | |
cavities | |
end | |
def replace_cavities_with(symbol) | |
self.cavities.each do |coords| | |
@grid[coords[0]][coords[1]] = symbol | |
end | |
end | |
def is_cavity?(row, column) | |
ary = [] | |
ary << @grid[row - 1][column] | |
ary << @grid[row][column - 1] | |
ary << @grid[row][column + 1] | |
ary << @grid[row + 1][column] | |
ary.max < @grid[row][column] | |
end | |
def size | |
@size ||= @grid.size | |
end | |
def to_s | |
@grid.each { |ary| puts ary.join } | |
end | |
end | |
n = gets.strip.to_i | |
grid = Array.new(n) | |
for grid_i in (0..n-1) | |
grid[grid_i] = gets.strip.split('').map(&:to_i) | |
end | |
cavity_finder = CavityFinder.new(grid) | |
cavity_finder.replace_cavities_with('X') | |
cavity_finder.to_s |
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
class StoneFinder | |
attr_accessor :stones, :diff_a, :diff_b | |
def initialize(stones, diff_a, diff_b) | |
@stones = stones | |
@diff_a = diff_a | |
@diff_b = diff_b | |
end | |
def possible_last_values | |
last_values = [] | |
last_values << (self.stones - 1) * self.diff_a | |
(self.stones - 1).times do |n| | |
new_val = last_values[0] - (n + 1) * self.diff_a + (n + 1) * self.diff_b | |
last_values << new_val | |
end | |
last_values.uniq.sort | |
end | |
end | |
num_tests = gets.strip.to_i | |
tests = [] | |
i = 0 | |
while i < num_tests | |
num_stones = gets.strip.to_i | |
diff_a = gets.strip.to_i | |
diff_b = gets.strip.to_i | |
tests << StoneFinder.new(num_stones, diff_a, diff_b) | |
i += 1 | |
end | |
tests.each do |test| | |
puts test.possible_last_values.join(' ') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment