Skip to content

Instantly share code, notes, and snippets.

@thepug
Forked from spilledmilk/imgblur-refactor.rb
Created August 31, 2017 15:37
Show Gist options
  • Save thepug/4f8291742819998627d123b92f66373e to your computer and use it in GitHub Desktop.
Save thepug/4f8291742819998627d123b92f66373e to your computer and use it in GitHub Desktop.
Refactored code for Image Blur challenges (incl. Manhattan Distance)
class Image
attr_accessor :array
def initialize(array)
@array = array
end
def blur(distance = 1)
distance.times do
transform
end
end
def output_image
@array.each {|item| puts "#{item.join()}"}
end
private
def transform
# length of one secondary array
width = array[0].length
# number of secondary arrays (rows)
height = array.length
ones_array = []
array.each_with_index do |row, y|
row.each_with_index do |value, x|
ones_array << [x, y] if value == 1
end
end
ones_array.each do |coordinate|
x, y = coordinate
array[y][x + 1] = 1 unless (x + 1 >= width)
array[y][x - 1] = 1 unless (x - 1 < 0)
array[y + 1][x] = 1 unless (y + 1 >= height)
array[y - 1][x] = 1 unless (y - 1 < 0)
end
end
end
image = Image.new([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
])
image.blur(3)
image.output_image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment