Ruby 不使用内置方法的二维数组转置
Ruby 2D array transpose without using built in method
我已经坚持了一段时间。作为一项任务,我需要在不使用内置转置方法且不更改函数名称/输出的情况下转置此二维数组。我觉得它应该比我想象的要容易得多...
class Image
def transpose
@array.each_with_index do |row, row_index|
row.each_with_index do |column, col_index|
@array[row_index] = @array[col_index]
end
end
end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print "Image transpose"
puts
image_transpose.output_image
puts "-----"
image_transpose.transpose
image_transpose.output_image
puts "-----"
试试下面的代码:
class Image
def initialize(array)
@array = array
end
def transpose
_array = @array.dup
@array = [].tap do |a|
_array.size.times{|t| a << [] }
end
_array.each_with_index do |row, row_index|
row.each_with_index do |column, col_index|
@array[row_index][col_index] = _array[col_index][row_index]
end
end
end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
image_transpose.transpose
我建议您将方法 transpose
替换为以下内容。
def transpose
@array.first.zip(*@array[1..-1])
end
对(未定义的)方法 output_input
的需求并不明显。当然,您还需要一个 initialize
方法来为实例变量赋值 @array
.
我假设您被要求改进方法的实现 transpose
;否则就没有理由规定你不能使用Ruby的built-intranspose
方法。
我已经坚持了一段时间。作为一项任务,我需要在不使用内置转置方法且不更改函数名称/输出的情况下转置此二维数组。我觉得它应该比我想象的要容易得多...
class Image
def transpose
@array.each_with_index do |row, row_index|
row.each_with_index do |column, col_index|
@array[row_index] = @array[col_index]
end
end
end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print "Image transpose"
puts
image_transpose.output_image
puts "-----"
image_transpose.transpose
image_transpose.output_image
puts "-----"
试试下面的代码:
class Image
def initialize(array)
@array = array
end
def transpose
_array = @array.dup
@array = [].tap do |a|
_array.size.times{|t| a << [] }
end
_array.each_with_index do |row, row_index|
row.each_with_index do |column, col_index|
@array[row_index][col_index] = _array[col_index][row_index]
end
end
end
end
image_transpose = Image.new([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
image_transpose.transpose
我建议您将方法 transpose
替换为以下内容。
def transpose
@array.first.zip(*@array[1..-1])
end
对(未定义的)方法 output_input
的需求并不明显。当然,您还需要一个 initialize
方法来为实例变量赋值 @array
.
我假设您被要求改进方法的实现 transpose
;否则就没有理由规定你不能使用Ruby的built-intranspose
方法。