[SOLVED] Looking for a cleaner way to get a winner on a Tic Tac Toe Game


This Content is from Stack Overflow. Question asked by Joji

I am writing a function that takes a 2d array that represents a grid for a tic tac toe game. Initially it is [[0, 0, 0], [0, 0, 0], [0, 0, 0]] and there is player 1 which is represented as 1 and player 2 as -1.

The function to check the winner should return the winner if there is actually a winner.

My attempt is this:

  const checkIfWin = (b) => {
    if (b[0][0] == b[0][1] && b[0][1] == b[0][2]) return b[0][0]
    if (b[1][0] == b[1][1] && b[1][2] == b[1][1]) return b[1][0]
    if (b[2][0] == b[2][1] && b[2][1] == b[2][2]) return b[2][2]
    if (b[0][0] == b[1][0] && b[1][0] == b[2][0]) return b[2][0]
    if (b[0][1] == b[1][1] && b[1][1] == b[2][1]) return b[2][1]
    if (b[0][2] == b[1][2] && b[1][2] == b[2][2]) return b[2][2]
    if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) return b[2][2]
    if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) return b[2][0]

checkIfWin([ [ 1, 0, 0 ], [ 0, 1, 0 ], [ -1, -1, 1 ] ]) // 1

It works but I don’t think it is really elegant or clean and I wonder if there is a better way to check a winner and return the winner?


  1. Use two helper functions: checkRow(i) and checkColumn(i), which check if all values are same in a given row and column respectively.
  2. For i in range [0, number of rows], use checkRow(i)
  3. For i in range [0, number of columns], use checkColumn(i)
  4. If still no winner is found, check the diagonals (for which you can use another helper function)

This is extremely simple to program, so I’ll leave that up to you. But you can use this approach to break down the problem into simpler pieces.

This Question was asked in StackOverflow by Joji and Answered by Abhinav Mathur It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?