# Tic-tac-toe checking

**URL:** <https://rubytalk.org/t/tic-tac-toe-checking/21610>\
**Category:** ruby-talk\
**Created:** [17 October 2005 14:17 UTC](https://rubytalk.org/t/tic-tac-toe-checking/21610 "2005-10-17T14:17:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brown\_Warren](https://avatars.discourse-cdn.com/v4/letter/b/73ab20/32.png) [@Brown\_Warren](https://rubytalk.org/u/Brown_Warren)\
**Post date:** [17 October 2005 14:17 UTC](https://rubytalk.org/t/tic-tac-toe-checking/21610/1 "2005-10-17T14:17:12Z")

</div>

CBlair1986,

> I'd like to be able to check for a X-in-a-row win on a  
> Y-by-Y board. I'd eventually like to be able to check  
> for a 10-in-a-row on a 50-by-50 board. Are there any  
> easy methods I could use, besides doing a check for  
> each possible win?

&nbsp;&nbsp;&nbsp;&nbsp;Well, if you only need to check for a win after someone moves, you  
can just perform four checks for the up/down/diagonal1/diagonal2 cases  
for up to X squares away from the last move.

&nbsp;&nbsp;&nbsp;&nbsp;If instead you don't know the last move and need a generic algorithm  
to see if player A has a win, a simple one is to initialize a YxY array  
to zeros, then loop over each row/column. For each square where player  
A has played, increment the four squares: same row next column; next row  
previous column; next row same column; and next row next column. Or,  
put another way:

123  
456  
789

&nbsp;&nbsp;&nbsp;&nbsp;If player A has played in square 5, increment squares 6, 7, 8, and  
9. After each increment, test for a value equal to X, indicating a  
player A win. If you need to check for a player B win, you'll need to  
use the same algorithm on a separate array. If you have a player C,  
you'll need a third array, etc.

&nbsp;&nbsp;&nbsp;&nbsp;This algorithm is O(Y^2), so it won't scale well when Y becomes  
large, but for a 50x50 board, your only talking about 2,500 iterations,  
which should be fine.

&nbsp;&nbsp;&nbsp;&nbsp;I hope this helps.

&nbsp;&nbsp;&nbsp;&nbsp;- Warren Brown
