[Edit: a couple of days ago an anonymous user proposed an edit that was rejected by two members, both on the grounds that "the edit deviates from the original intent of the post." While I'm sure those members had good intentions, neither appears to have experience with Ruby, so I don't understand how they were able to arrive at that conclusion.
The anonymous user was not just improving my code, he or she was correcting an error I made. It was a good catch and a good fix. I've edited to incorporate the fix (and made a few other small changes).
If you are that anonymous user, please accept my thanks. A small suggestion: it probably would have been better if you had just left a comment, but the main thing is that the code is now fixed. (I hope.)]
You can also use Ruby's Matrix and Vector classes to see if player p
wins. In the following, square[i][j]
is the player in row i
, column j
.
Code
require 'matrix'
def win?(square,p)
n = square.size
m = Matrix[*square]
pvec = Matrix.build(1,n){p}.row(0)
m.row_vectors.any? { |r| r == pvec } ||
m.column_vectors.any? { |c| c == pvec } ||
Vector[*m.each(:diagonal).to_a] == pvec ||
n.times.all? { |i| square[i][n-i-1] == p }
end
Example
square = [[1,3,2],
[4,2,6],
[2,8,9]]
win?(square, 2) #=> true
win?([[1,3,2],[4,3,6],[2,3,9]], 3) #=> true
win?([[1,3,2],[3,3,3],[2,7,9]], 3) #=> true
win?([[1,3,2],[4,5,6],[7,8,9]], 1) #=> false
Explanation
pvec = Matrix.build(1,n){p}.row(0)
creates a vector for which every element is the value of the player argument p
(e.g., pvec # => Vector[2,2,2]
).
m.row_vectors.any? { |r| r == pvec }
determines if player p
wins in any row,
m.column_vectors.any? { |c| c == pvec }
determines if player p
wins in any column,
Vector[*m.each(:diagonal).to_a] == pvec
determines if player p
wins on the main diagonal, and
(0...n).all? { |i| square[i][n-i-1] == p }
determines if player p
wins on the minor diagonal (top right to bottom left).
I was unable to find a way to check the minor diagonal using Matrix
class methods.