T
T
Tarasov Konstantin2014-06-07 20:03:42
Java
Tarasov Konstantin, 2014-06-07 20:03:42

Matrix three by three, how to quickly check if the elements of any column/row/diagonal match?

I am writing a program for playing tic-tac-toe, how to check that someone lined up 3 elements in a row and the game is won? The only thing that comes to mind is to separately compare each column \ row \ diagonal for equality, but this is a beard, can you tell me something smarter?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Ndochp, 2014-06-11
@Ndochp

IMHO for a field of arbitrary dimension, it is necessary to check not the field, but the move. Since the number of winning combinations with the growth of the field will grow very badly. I think it is necessary to check each move, whether it led to a victory.
That is, after each move, we sequentially check
1. the length of the diagonal of the crosses upright + downleft+1
2. the length of the diagonal of the crosses upleft+downright+1
3. the length of the diagonal of the crosses right+left+1
4. the length of the diagonal of the crosses down+up + 1
If at least one direction more than the target value (on an unlimited field like 5 in a row play), then the player wins.

T
Timur, 2014-06-09
@timych

If I correctly understood the proposed lumierecyril option, then it is not quite working. Imagine that the cross is on the cells with indices 0, 5, 8. In theory, if you put the cross on index 4, the player won. But in this case it is not. When concatenating indices with crosses, we get 0, 4, 5, since, according to the proposed logic, we run through the cells sequentially and collect options from three-digit numbers. My variant - each time to collect a line from indexes containing a cross (or a zero depending on the player). Then, given an array of winning combinations, check if each digit of the combination is present in the concatenated string of indexes with crosses (operate with String) . If there are all three matches, then the player has won. There is another option - run twice in a loop with a nested loop on the playing field, accumulating the results each time into two lists according to the conditions - matching horizontally, diagonally to the left, then vertically and diagonally to the right. If at least one list has a length equal to the number of cells on the side of the playing field, then the player has won.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question