Skip to content

Instantly share code, notes, and snippets.

@cowplace
Created October 12, 2014 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowplace/a4eb0b149747633346a8 to your computer and use it in GitHub Desktop.
Save cowplace/a4eb0b149747633346a8 to your computer and use it in GitHub Desktop.
require 'pp'
class RotateMatrix
OFFSETS = [
[1,0],
[1,1],
[0,1],
[-1,1],
[-1,0],
[-1,-1],
[0,-1],
[1,-1]
]
def initialize
@moved = []
@matrix = [
%w(a b c d e),
%w(f g h i j),
%w(k l m n o),
%w(p q r s t),
%w(u v w x y),
]
end
def execute(cmd)
cmd.each_char do |chr|
rotate(chr)
end
print_result
end
private
def rotate(chr)
@moved = select_move_cells(position(chr))
tmp_matrix = Marshal.load(Marshal.dump(@matrix))
@moved.rotate(rotate_direction(chr)).zip(@moved).each do |pos_pair|
after = pos_pair.first
before = pos_pair.last
tmp_matrix[after.first][after.last] = @matrix[before.first][before.last]
end
@matrix = tmp_matrix
end
def position(chr)
target = chr.downcase
@matrix.each_with_index do |row,idx1|
row.each_with_index do |elem,idx2|
if elem === target then
return [idx1, idx2]
end
end
end
end
def select_move_cells(base)
OFFSETS.map { |offset|
calc_pos(base, offset)
}.select { |pos|
check_range(pos)
}
end
def calc_pos(base, offset)
[base.first+offset.first, base.last+offset.last]
end
def check_range(pos)
(0...5).include?(pos.first) && (0...5).include?(pos.last)
end
def rotate_direction(chr)
if upcase?(chr) then
1
else
-1
end
end
def upcase?(chr)
chr.upcase === chr
end
def print_result
# pp @matrix
puts @moved.map{|pos| @matrix[pos.first][pos.last]}.sort.join
end
end
if __FILE__ === $0 then
ins = RotateMatrix.new
ins.execute(ARGV.first)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment