gpt4 book ai didi

arrays - 仅在索引存在时编辑索引

转载 作者:数据小太阳 更新时间:2023-10-29 07:17:38 25 4
gpt4 key购买 nike

我需要创建一个代表图像的 0 和 1 的二维网格,并创建一个模糊方法,将 1 旁边的任何 0(左、右、上或下)更改为 1,如下所示:

0000 => 0000
0000 0010
0010 0111
0000 0010

接下来,我必须允许用户传入一个数字,以允许模糊在每个方向上扩展多个空间。如果我调用 image.blur(2),它会在每个方向上扩展 2 个空格,但每个第一步都必须再次调用 blur 以说明对角线。例如:

00000000 => 00010000
00000000 00111000
00010000 01111100
00000000 00111000
00000000 00010000

这是我的代码。

class Image
attr_accessor :picture
def initialize(*rows)
@picture = *rows
end
def output_image
@picture.each_index do |i|
puts @picture[i].join
end
end
def blur(distance=1)
@blurred_image = Array.new(@picture.length, 0) {Array.new(@picture[0].length, 0)} #create new array of zeroes the size of @picture
@picture.each_index do |i|
@picture[i].each_index do |j|
if @picture[i][j] == 1
@blurred_image[i][j] = 1 if @blurred_image[i][j]
@blurred_image[i][j-1] = 1 if @blurred_image[i][j-1]
@blurred_image[i][j+1] = 1 if @blurred_image[i][j+1]
@blurred_image[i-1][j] = 1 if @blurred_image[i-1][j]
@blurred_image[i+1][j] = 1 if @blurred_image[i+1][j]
end
end
end
if distance > 1
@picture = @blurred_image #save progress of image blur in @picture so we can continue in recursive call
blur(distance-1) #iterate as long as distance > 1
elsif distance == 1 #necessary so blurred image isn't printed 'distance' times
@blurred_image.each_index do |i|
puts @blurred_image[i].join
end
end
end
end

pic = Image.new(
[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,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]
)
pic.blur(3)

我的函数有效,但前提是 1 没有超出数组的边界。如果我将 1 放在一个角落,看起来我的函数试图编辑一个不存在的索引的值,并且我收到以下消息:

image_blur.rb:28:in `block (2 levels) in blur': undefined method `[]' for nil:NilClass (NoMethodError)
from image_blur.rb:22:in `each_index'
from image_blur.rb:22:in `block in blur'
from image_blur.rb:21:in `each_index'
from image_blur.rb:21:in `blur'
from image_blur.rb:35:in `blur'
from image_blur.rb:35:in `blur'
from image_blur.rb:47:in `<main>'

我试图告诉它仅在索引存在时才将 1 分配给该索引。如果有任何帮助,我将不胜感激。

最佳答案

看起来您在检查一层深度之前尝试检查两层深度。

例如 picture[1] 可能不存在...所以如果您随后尝试检查 picture[i][j] 它会失败。

您可以尝试在索引之前检查每个级别是否存在...

if @picture[i] && @picture[i][j] && @picture[i][j] == 1
if @blurred_image[i].present?
@blurred_image[i][j] = 1 if @blurred_image[i][j]
@blurred_image[i][j-1] = 1 if @blurred_image[i][j-1]
@blurred_image[i][j+1] = 1 if @blurred_image[i][j+1]
end
@blurred_image[i-1][j] = 1 if @blurred_image[i-1] && @blurred_image[i-1][j]
@blurred_image[i+1][j] = 1 if @blurred_image[i+1] && @blurred_image[i+1][j]

关于arrays - 仅在索引存在时编辑索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com