【发布时间】:2016-08-27 21:06:37
【问题描述】:
类 Image 使用 0 和 1 的数组进行初始化。我有方法transform,这样
[[0,0,0],
[0,1,0],
[0,0,0]]
返回
[[0,1,0],
[1,1,1],
[0,1,0]]
我想实现方法blur(n),它用transform迭代n次,比如用
调用blur(2)[[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,1,0,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,1,1,1,1,1,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,0,1,0,0,0,0]]
我正在尝试迭代地使用转换来实现这一点,但是当使用 Image 的实例调用模糊时,我得到了 undefined method 'map' for #<Context::Image:0x000000012eb020>。如何迭代每个连续的转换,以便模糊返回具有最大 n 个转换的最新版本?
class Image
attr_accessor :array
def initialize(array)
self.array = array
end
def output_image
self.array.each do |item|
puts item.join
end
end
def transform #changes adjacent a 1's adjacent 0's into 1
cloned = self.array.map(&:clone)
#scan original array for 1; map crosses into clone if found
self.array.each.with_index do |row, row_index|
row.each.with_index do |cell, col|
if cell == 1
cloned[row_index][col+1] = 1 unless col+1 >= row.length #copy right
cloned[row_index+1][col] = 1 unless row_index+1 >= cloned.length # copy down
cloned[row_index][col-1] = 1 unless col.zero? # copy left
cloned[row_index-1][col] = 1 unless row_index.zero? #copy up
end
end
end
cloned
end
def blur(n) #should call transform iteratively n times
blurred = Image.new(self)
n.times do
blurred = blurred.transform
end
blurred
end
end
【问题讨论】:
标签: ruby algorithm class iteration