配列の配列(つまり行列)内の行または列の入れ替えが必要です。私はオンラインこのスワップ方法を発見した、と私はboard.matrix
は、配列の配列である私のmutate
機能、でそれを拡張:Ruby行列の列または行の入れ替え
# 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