与Array#pop()
类似,我想创建一个删除矩阵最后一列的破坏性方法:Matrix#hpop()
(h代表水平)。
如何使此方法具有破坏性?没有像Matrix#replace()
这样的方法可以用来修改对象的内部状态。
# Removes trailing columns from a Matrix.
# @param number_of_columns [Integer] number of trailing columns to be removed
# @return [Matrix] matrix
# @raise [ErrDimensionMismatch] if Matrix does not have enough columns for operation
def hpop(number_of_columns = 1)
Matrix.Raise ErrDimensionMismatch unless number_of_columns < self.column_count
columns = []
last_column_to_be_included = self.column_count - number_of_columns
self.column_vectors.each_with_index do |column, index|
break if index + 1 > last_column_to_be_included
columns << column.to_a
end
Matrix.columns(columns) # should be destructive
end
答案 0 :(得分:3)
您可以修补Matrix类以删除列...
class Matrix
def drop_column
@rows.each {|r| r.pop}
end
end
my_matrix = Matrix.build(3,5) { 1 }
=> Matrix[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
my_matrix.drop_column
p my_matrix
=> Matrix[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
或类似地删除一行
class Matrix
def drop_row
@rows.pop
end
end
修改
所以实际上hpop会......
def hpop(number_of_columns = 1)
Matrix.Raise ErrDimensionMismatch unless number_of_columns < column_count
dropped_columns = []
number_of_columns.times do
dropped_column = []
@rows.each {|r| dropped_column << r.pop}
dropped_columns << dropped_column
end
@column_count -= number_of_columns
Matrix.columns(dropped_columns.reverse)
end
(代码来自您自己的来源,只是添加了@column_count -= ...
行)
编辑#2
vpop方法可能会......
class Matrix
def vpop(number_of_rows = 1)
Matrix.Raise ErrDimensionMismatch unless number_of_rows < @rows.size
dropped_rows = []
number_of_rows.times { dropped_rows.unshift @rows.pop }
Matrix.columns(dropped_rows)
end
end