在Ruby矩阵中交换列或行

时间:2011-01-30 20:17:58

标签: ruby arrays matrix multidimensional-array transpose

我想在数组数组(即矩阵)中交换行或列。我在网上找到了这个交换方法,并用mutate函数扩展了它,其中board.matrix是数组数组:

# Swap to elements of an Array
def swap!(a,b)
  self[a], self[b] = self[b], self[a]
  self
end

def mutate(board)
  matrix = board.matrix
  random = rand
  rand_a = rand(matrix.length-1)
  rand_b = rand(matrix.length-1)

  puts "Old one:"
  board.print_matrix
  # We have a 50:50 chance of swapping either columns or rows
  if random <= 0.5
    # Swap columns: Transpose first
    puts "Swapping columns #{rand_a} and #{rand_b}..."
    temp = matrix.transpose
    temp.swap!(rand_a, rand_b)
    matrix = temp.transpose
  else
    # Just swap rows
    puts "Swapping rows #{rand_a} and #{rand_b}..."
    matrix.swap!(rand_a, rand_b)
  end
  puts "New one:"
  board.print_matrix
end

现在它为行做了它应该做的事情:

Old one:
X  X  0  0  
0  0  0  0  
X  X  0  0  
0  0  0  0  

Swapping rows 1 and 0...
New one:
0  0  0  0  
X  X  0  0  
X  X  0  0  
0  0  0  0

但它不适用于专栏。那是为什么?

Old one:
0  X  X  0  
0  0  X  0  
X  0  0  0  
0  0  0  0  

Swapping columns 1 and 0...
New one:
0  X  X  0  
0  0  X  0  
X  0  0  0  
0  0  0  0

2 个答案:

答案 0 :(得分:2)

因为在下面的代码中你没有转换数组matrix所指向的代码,你刚刚为matrix分配了一个新的数组,这是一个局部变量:

temp = matrix.transpose
temp.swap!(rand_a, rand_b)
matrix = temp.transpose

您实际上可以用以下代码替换此代码:

matrix.each do |row|
    row[rand_a], row[rand_b] = row[rand_b], row[rand_a]
end

答案 1 :(得分:2)

问题是您只将局部变量matrix设置为#transpose创建的新对象。

然后你打印了原始矩阵对象,显然是board.matrix

虽然您也使用局部变量来交换行,但在这种情况下,本地是对原始对象的引用,因此它们是相同的,并且从输出例程的角度来看它“起作用”。但是对于列,transpose返回了一个新对象,而board从未更新。