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