Created
October 13, 2014 04:28
-
-
Save ymmtmdk/8324e3b9d7e73bfd0f99 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
class Cell | |
attr_accessor :x,:y,:chr | |
def initialize(x,y,chr) | |
@x,@y,@chr = x,y,chr | |
end | |
def ==(c) | |
@chr == c | |
end | |
def inspect | |
@chr | |
end | |
end | |
class Sheet | |
def initialize(size = 5) | |
@size = size | |
chr = 'a' | |
@cells = @size.times.map{|y| | |
@size.times.map{|x| | |
cell = Cell.new(x, y, chr.dup) | |
chr.succ! | |
cell | |
} | |
} | |
end | |
def get(x,y) | |
return nil if x < 0 || x >= @size || y < 0 || y >= @size | |
@cells[y][x] | |
end | |
def around(x,y) | |
a = [[-1,-1],[0,-1],[1,-1], [1,0],[1, 1],[0, 1],[-1, 1],[-1,0]] | |
a.map{|ax,ay| | |
get(x+ax, y+ay) | |
}.compact | |
end | |
def rotate!(x,y, is_reverse=false) | |
cells = around(x,y) | |
copy = cells.map{|cl| cl.dup} | |
cells.size.times{|i| | |
idx = is_reverse ? i+1 : i-1 | |
idx %= cells.size | |
cells[i].chr = copy[idx].chr | |
} | |
end | |
def find(c) | |
down_c = c.downcase | |
@cells.flatten.find{|e| e == down_c} | |
end | |
def rotate_by_chr!(c) | |
cell = find(c) | |
is_upper = c != c.downcase | |
rotate!(cell.x, cell.y, is_upper) | |
end | |
def rotate_by_string!(str) | |
str.each_char{|c| rotate_by_chr!(c)} | |
end | |
end | |
def answer(str) | |
sheet = Sheet.new | |
sheet.rotate_by_string!(str) | |
cell = sheet.find(str[-1,1]) | |
sheet.around(cell.x, cell.y).map{|cl| cl.chr}.sort.join | |
end | |
if __FILE__ == $0 | |
p answer("a") | |
p answer("b") | |
p answer("m") | |
p answer("mg") | |
p answer("Mg") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment