如何将每个循环应用于每个项目?

时间:2021-05-16 14:30:35

I'm working on a problem called Image Blur. I need to have my code take items (either 1s or 0s) from a 2D array and, for every 1, change the adjacent 0s to 1s. My code thus far does this well to the first 1 that it comes across, but for some reason it does not loop over the others.

我正在研究一个名为Image Blur的问题。我需要让我的代码从2D数组中获取项目(1或0),并且每1个,将相邻的0更改为1。到目前为止,我的代码对它遇到的第一个代码做得很好,但由于某种原因它不会循环其他代码。

class Image
  def initialize(image)
    @values = image
  end

  def find_ones
    ones = []
    @values.each_with_index do |row, row_index|
      row.each_with_index do |pixel, column_index|
        if pixel == 1
          coord = [row_index, column_index]
          ones << coord
        end
        puts "#{pixel} #{row_index} #{column_index}" if pixel == 1
      end
    end
    ones
  end

  def transform
    ones = find_ones
    ri = ones[0][0]
    ci = ones[0][1]
    ones.each do 
      @values[ri + 1][ci] = 1 if (ri + 1) <= 3
      @values[ri - 1][ci] = 1 if (ri - 1) >= 0
      @values[ri][ci + 1] = 1 if (ci + 1) <= 3
      @values[ri][ci - 1] = 1 if (ci - 1) >= 0
    end
  end


 def output_image
    @values.each do |row|
      puts row.join
    end
  end
end


image = Image.new([
  [0, 0, 0, 1],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 1, 0, 0]
])

image.transform
image.output_image

Thanks for the help in advance!

我在这里先向您的帮助表示感谢!

1 个解决方案

#1


0  

Well your ones.each do goes through the ones but ignores them, since your block doesn't have parameters. You essentially just use ones to determine how often to run the block.

那么你的那些。虽然你的块没有参数,但它们会通过这些但忽略它们。您基本上只使用它来确定运行块的频率。

Your

ri = ones[0][0]
ci = ones[0][1]
ones.each do 

should be

ones.each do |ri, ci|

I'm surprised you got find_ones right (where you do something similar) but do something so strange in transform (setting ri and ci like that).

我很惊讶你有find_ones正确(你做了类似的事情)但在变换中做了一些如此奇怪的事情(设置ri和ci就是这样)。

#1


0  

Well your ones.each do goes through the ones but ignores them, since your block doesn't have parameters. You essentially just use ones to determine how often to run the block.

那么你的那些。虽然你的块没有参数,但它们会通过这些但忽略它们。您基本上只使用它来确定运行块的频率。

Your

ri = ones[0][0]
ci = ones[0][1]
ones.each do 

should be

ones.each do |ri, ci|

I'm surprised you got find_ones right (where you do something similar) but do something so strange in transform (setting ri and ci like that).

我很惊讶你有find_ones正确(你做了类似的事情)但在变换中做了一些如此奇怪的事情(设置ri和ci就是这样)。