Last active
December 26, 2017 03:55
-
-
Save dscataglini/315a13d1980d076989d366ccebacb332 to your computer and use it in GitHub Desktop.
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
class BitmapEditor | |
VALID_SIZE_RANGE = (1..250) | |
DEFAULT_COLOR = 'O' | |
def clear(c = cols, r = rows) | |
return unless VALID_SIZE_RANGE === r && | |
VALID_SIZE_RANGE === c | |
@bitmap = Array.new(r) { Array.new(c) { DEFAULT_COLOR }} | |
end | |
def color(x, y, color = DEFAULT_COLOR) | |
@bitmap[y - 1][x - 1] = color if pixel_exists?(x - 1, y - 1) | |
end | |
def color_row(x1, x2, y, color) | |
(x1..x2).each do |x| | |
color(x, y, color) | |
end | |
end | |
def color_col(x, y1, y2, color) | |
(y1..y2).each do |y| | |
color(x, y, color) | |
end | |
end | |
def to_s | |
@bitmap.map { |el| el.join }.join("\n") | |
end | |
def output | |
return unless @bitmap | |
puts self.to_s | |
end | |
private | |
def rows | |
@bitmap ? @bitmap.length : 0 | |
end | |
def cols | |
@bitmap ? @bitmap.first.length : 0 | |
end | |
def pixel_exists?(x, y) | |
(0..cols - 1) === x && (0..rows - 1) === y | |
end | |
end | |
class Handler | |
def initialize(editor = BitmapEditor.new, parser_class = Parser) | |
@editor = editor | |
@parser = parser_class.new(@editor) | |
end | |
def run(file) | |
return puts "please provide correct file" if file.nil? || !File.exists?(file) | |
File.open(file).each do |line| | |
@parser.parse(line) | |
end | |
end | |
end | |
class Parser | |
VALID_COMMANDS = /^(C|S|I|L|V|H)\s?(\d{1,3})?\s?(\d{1,3})?\s?([0-9A-Z]{1,3})?\s?([A-Z])?/ | |
COMMANDS = { | |
'C' => :clear, | |
'S' => :output, | |
'I' => :clear, | |
'L' => :color, | |
'V' => :color_col, | |
'H' => :color_row | |
} | |
def initialize(editor) | |
@editor = editor | |
end | |
def parse(line) | |
matchdata = VALID_COMMANDS.match(line) | |
if matchdata | |
command, *args = matchdata.captures.compact.map { |el| el =~ /\d{1,3}/ ? el.to_i : el } | |
@editor.send(COMMANDS[command], *args) | |
end | |
end | |
end | |
c = Parser.new(BitmapEditor.new) | |
s = <<-EOF | |
I 5 6 | |
L 1 3 A | |
V 2 3 6 W | |
H 3 5 2 Z | |
S | |
EOF | |
s.each_line { |e| c.parse(e) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment