Skip to content

Instantly share code, notes, and snippets.

@esterlus
Created September 22, 2015 13:37
Show Gist options
  • Save esterlus/44b1241b88173a3aa451 to your computer and use it in GitHub Desktop.
Save esterlus/44b1241b88173a3aa451 to your computer and use it in GitHub Desktop.
ruby coding challenge
class Canvas
attr_reader :width
attr_reader :height
def initialize(input)
vals = input.split
@width = vals[0].to_i
@height = vals[1].to_i
@all = Array.new(@width * @height, 0)
end
def applyPiece(p)
(p.y .. p.y + p.height - 1).each do |y|
indexstart = y * @width
(indexstart + p.x .. indexstart + p.x + p.width - 1).each do |i|
@all[i] = p.color
end
end
end
def countColors()
colors = Hash.new(0)
@all.each do |x|
colors[x] += 1
end
return colors
end
end
class Piece
attr_reader :color
attr_reader :x
attr_reader :y
attr_reader :width
attr_reader :height
def initialize(input)
vals = input.split
@color = vals[0].to_i
@x = vals[1].to_i
@y = vals[2].to_i
@width = vals[3].to_i
@height = vals[4].to_i
end
end
def readInput
inputs = Array.new
i = ' '
loop do
i = gets.chomp
break if i.empty?
inputs.push(i)
end
return inputs
end
puts 'Input canvas: width height'
input_canvas = gets.chomp
puts 'Input any pieces in this format: color x y width height'
puts 'Input empty to calculate color occurances.'
inputs = readInput
canvas = Canvas.new(input_canvas)
inputs.each do |i|
canvas.applyPiece(Piece.new(i))
end
# puts canvas.inspect
col = canvas.countColors
col.keys.sort.each do |k|
puts('%s %s' % [ k, col[k]])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment