作者goodplace (hello)
看板Ruby
標題[問題] 關於Array
時間Thu Oct 22 19:43:21 2009
環境:
Ruby 1.9.1
狀況:
得到非預期的結果
附錄:
以下是我的code:
$ans = []
def perm(a,n,k,t)
if t == k
p a
$ans << a
else
0.upto(n-1){|i|
a[t] = i
perm(a, n-i, k, t + 1)
}
end
end
a = []
perm(a,2,2,0)
p $ans
*************
output 竟然是:
[0, 0]
[0, 1]
[1, 0]
[[1, 0], [1, 0], [1, 0]]
應該是
[0, 0]
[0, 1]
[1, 0]
[[0, 0], [0, 1], [1, 0]]
才對不是嗎?
我只不過把"a" push進array $ans,
為什麼最後每個element都變得一樣?
用Ruby 1.8.6測試過 也是得到非預期的結果
謝謝各位看完我的問題!
希望能找到原因...(我花了一個小時卻找不出原因 ~_~)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.109.23.162
1F:推 godfat:因為你不斷改寫 a, $ans 實際上是 [a, a, a] 10/22 20:46
2F:→ godfat:因此 $ans << a 要改成 $ans << a.dup 才不會都是同個array 10/22 20:46
3F:→ poga:把a想成是個reference (光這樣講聽的懂就神了 10/22 20:47
4F:→ poga:噗,被搶先回正解了(遮臉 10/22 20:49
5F:→ godfat:我還有開 irb 測試哩(遮臉 10/22 20:52
6F:→ goodplace:感謝!! 10/22 21:07