Reputation: 55
Hi I created a program that has one dimensional array that can hold 9 elements and enum mark(O,X). this encoding scheme sets the first move to x and then o in the array etc... My problem is I want to make my getWinner() method that calculates the winner more efficient. currently I just have a bunch of if else statements, how can I reduce the lines of code and make it in a more "smarter way".
Upvotes: 0
Views: 2052
Reputation: 1
I found a page that implements this game. http://www.lightbluelab.com/enjoy/ai/tic-tac-toe/ I don't know the algorithm it uses, but I think it maybe a reference for you because it is written in JavaScript and the source codes should be available.
Upvotes: 0
Reputation: 70387
You could very easily group the vertical and horizontal checks into a pair of loops. For example:
// Horizontal test
for (int i = 0; i < 3; i++) {
if (getMark(i, 0) == getMark(i, 1)
&& getMark(i, 1) == getMark(i, 2) && getMark(i, 2) != null)
result = getMark(i, 0)
// ...
// Vertical test
for (int i = 0; i < 3; i++) {
if (getMark(0, i) == getMark(1, i)
&& getMark(1, i) == getMark(2, i) && getMark(2, i) != null)
result = getMark(0, i)
This in and of itself takes six of your if statements and reduces them to two.
Upvotes: 1
Reputation: 541
Well, for starters, it'd be better to stop the execution of getWinner() as soon as it finds a Tic-Tac-Toe, instead of continuing searching even after it's been found. You can do that by, within each of your if statements, including a return result;
statement at the end.
But anyway, here's an idea for efficiency: every time a player makes a move (X, for example), only check the other squares it could make a Tic-Tac-Toe with for other X's. You'll have to do some thinking about how to implement the logic, but it would keep you from having to check every single set of 3 squares on the board, every time.
Upvotes: 1