更改多维数组中的元素

时间:2015-03-05 04:40:45

标签: ruby arrays

在内部数组中,我有0个和1

class Image
  def initialize(rows)
    @rows = rows
  end
end

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

我希望上,下,左,右的数字也可以转为1。我试图通过操纵column_indexrow_index来做到这一点。代码是:

class Image
  def blur
    @rows_copy = Array.new(@rows.size) {Array.new(@rows.first.size)}
    @rows.each_with_index do |row, row_index|
      row.each_with_index do |cell, column_index|
        blur_location(row_index,column_index)
      end
    end
    @rows = @rows_copy
  end
  def blur_location (row_index, column_index)
    if @rows[row_index][column_index] == 1
      @rows_copy[row_index][column_index] = 1
      @rows_copy[row_index + 1][column_index] = 1
      @rows_copy[row_index - 1][column_index] = 1
      @rows_copy[row_index][column_index + 1] = 1
      @rows_copy[row_index][column_index - 1] = 1
    else
      @rows_copy[row_index][column_index] = 0
    end
  end
  def output_image
    @rows.each_with_index do |row, row_index|
      puts row.join('')
    end
  end
end

image.blur
image.output_image

但只有一半的代码正常工作(即顶部和左侧转向1,而不是其他两个。)

1 个答案:

答案 0 :(得分:1)

代码几乎按预期工作,但您是以下代码段的受害者:

else
  @rows_copy[row_index][column_index] = 0
end

当您点击'1'时,您按预期设置了所有内容,但是当您继续前进并且您点击'1'附近的零(在您处理时向右和向下)时,您会发生什么正在将rows_copy重置为零。

以下是代码的修订版本,它做了正确的事情(注意副本首先设置为0,之后只标记1个):

#!/usr/bin/env ruby

class Image
  def initialize(rows)
    @rows = rows
  end

  def blur
    @rows_copy = Array.new(@rows.size) {Array.new(@rows.first.size)}
    @rows.each_with_index do |row, row_index|
      row.each_with_index do |cell, column_index|
        set_zero(row_index,column_index)
      end
    end
    @rows.each_with_index do |row, row_index|
      row.each_with_index do |cell, column_index|
        blur_location(row_index,column_index)
      end
    end
    @rows = @rows_copy
  end
  def set_zero(row_index, column_index)
     @rows_copy[row_index][column_index] = 0
  end
  def blur_location (row_index, column_index)
    if @rows[row_index][column_index] == 1
      @rows_copy[row_index][column_index] = 1
      @rows_copy[row_index + 1][column_index] = 1
      @rows_copy[row_index - 1][column_index] = 1
      @rows_copy[row_index][column_index + 1] = 1
      @rows_copy[row_index][column_index - 1] = 1
    end
  end
  def output_image
    @rows.each_with_index do |row, row_index|
      puts row.join('')
    end
  end
end

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

image.blur
image.output_image