1

I have a two-dimensional array, and I want to be able to use another array which refers to the column of the original one. I can do it with rows, but I can't figure out how to do it with columns.

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", " ", " "]]

I've tried using map! but that ends up causing the original twodim array to change when I just try to assign the columns to variables. I've also tried transpose but that returns a new array. Is there a way to create an array using the object id's from the original array in order to be able to modify it? This is for a tictactoe program, and I'm writing the ai for it. I'm trying to check if there's a way to win the game in a given row or column, then have it fill in the winning spot if it exists. Here's the rest of it if it helps:

    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 Answer 1

1

Use 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", " ", " "]] 

Explanation:

In your example, when doing col1[2] = "X" you are assigning to the object col1[2] a new variable with the value "X", that means that col1[2] is now storing the reference of the new object "X". However, when doing col1[2].replace("X") the method replace is changing the content of the object that is referenced by col12.

The following example will clarify the above explanation:

$> 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 !!!

I also recommend you to read this post: Is Ruby pass by reference or by value?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.