我創建了一個使用多維陣串列示矩陣的類。initialize 方法遍歷每個位置并將元素的值設定為指定的值,to_s 方法執行相同的操作,但它只是將每個元素連接到一個字串。我正在撰寫一個插入方法,該方法將給定位置的元素的值更改為給定值,但它更改了整個值而不僅僅是一個元素。
class Matrix
attr_accessor :rows, :cols, :arr
# Goes through the matrix setting everything with the "n" value
def initialize(r, c, n = "a")
@rows = r
@cols = c
@arr = Array.new(@rows)
tmpArray = Array.new(@cols)
i = 0
while i < @rows
j = 0
while j < @cols
tmpArray[j] = n
j = 1
end
@arr[i] = tmpArray
i = 1
end
return @arr
end
def to_s
i = 0
str = String.new
while i < @rows
j = 0
str << "("
while j < @cols
str << " "
if @arr[i][j].is_a?String
str << @arr[i][j]
else
str << @arr[i][j].to_s
end
j = 1
end
str << " )\n"
i = 1
end
return str
end
# Calls and prints to_s
def write
print self.to_s
return self.to_s
end
# Rewrites the element (r, c) as the value in "n"
def insert(r, c, n)
@arr[r][c] = n
self.write
return self
end
end
問題是,當我列印矩陣時,我注意到我不僅改變了一個元素,而且改變了矩陣的一整列。
a = Matrix.new(2, 2, 0)
a.insert(0, 0, 1)
a.write
# Expected output: ( 1 0 )
# ( 0 0 )
# Real output: ( 1 0 )
# ( 1 0 )
to_s 方法沒有失敗。我已經對它進行了跟蹤并對其進行了測驗。我正在列印矩陣位置的真實值。
uj5u.com熱心網友回復:
您的程式Array.new僅呼叫兩次,并且不使用任何其他方法創建陣列,也不使用dup或clone復制任何陣列。因此,您的程式中只有兩個不同的陣列物件。的每個元素@arr實際上都指向同一個行陣列。
解決方案的一個想法是替換這一行:
@arr[i] = tmpArray
有了這個:
@arr[i] = tmpArray.dup
但是,您的代碼很長,我還沒有嘗試運行它,所以我不知道這是否是一個完整的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362103.html
