二维数组,如何创建修改原始数组的列数组

时间:2014-03-16 00:03:34

标签: ruby arrays

我有一个二维数组,我希望能够使用另一个引用原始数组的数组。我可以用行来做,但我无法弄清楚如何使用列。

twodim = [[" "," "," "], [" "," "," "], [" "," "," "]]
row1 = twodim[0]
row1[0] = "X"

col1 = << twodim[0][0] << twodim[1][0] << twodim[2][0]
col1[2] = "X"

=> puts twodim
#actual result
=> [["X", " ", " "], [" ", " ", " "], [" ", " ", " "]]
#desired result
=> [["X", " ", " "], [" ", " ", " "], ["X", " ", " "]]

我尝试过使用地图!但是当我尝试将列分配给变量时,最终导致原始的twodim数组发生变化。我也尝试过转置,但会返回一个新数组。有没有办法使用原始数组中的对象id创建一个数组,以便能够修改它?这是一个tictactoe程序,我正在为它编写ai。我试图检查是否有一种方法可以在给定的行或列中赢得游戏,然后填写获胜点(如果存在的话)。如果有帮助的话,请参考其余部分:

    rows = [row1, row2, row3]
    cols = [col1, col2, col3]
    rows.map do |row|
        if !row.include?(@player) && row.count(@ai) == 2 then
            row.fill(@ai)
            return
        end
    end
    cols.each do |col|
        if !col.include?(@player) && col.count(@ai) == 2 then
            col.fill(@ai)
            puts "col = #{col}"
            return
        end
    end

1 个答案:

答案 0 :(得分:1)

使用String#replace

twodim = [[" "," "," "], [" "," "," "], [" "," "," "]]
row1 = twodim[0]
row1[0] = "X"
col1 = [twodim[0][0], twodim[1][0], twodim[2][0]]

col1[2].replace("X")

twodim
# => [["X", " ", " "], [" ", " ", " "], ["X", " ", " "]] 

说明:

在您的示例中,在执行col1[2] = "X"时,您正在为对象col1[2]分配一个值为"X"的新变量,这意味着col1[2]现在正在存储引用新对象"X"。但是,在执行col1[2].replace("X")时,方法replace正在更改col1 2引用的对象的内容。

以下示例将阐明上述说明:

$> col1[1].object_id
# => 2161281980 
$> col1[1] = "X"
# => "X" 
$> col1[1].object_id # Different object_id !!!
# => 2161469100
$> col1[1].replace("X")
# => "X" 
$> col1[1].object_id
# => 2161469100 # Same object_id !!!

我还建议您阅读这篇文章: Is Ruby pass by reference or by value?