Find the winner of Tic-Tac-Toe


Posted by Christy on 2023-01-20

Description: Write a function named winner, and return the winner of the Tic-Tac-Toe game

Example

winner([
['O', 'O', 'X'],
['O', 'X', 'X'],
['O', 'X', 'O']
]) 
// return O

winner([
['O', 'O', 'X'],
['O', 'X', 'X'],
['X', 'X', 'O']
]) 
// return X

winner([
['O', 'O', 'X'],
['O', 'O', 'X'],
['X', 'X', '']
])
// return draw

List all the possibilities would be great

// arr[0][0] arr[0][1] arr[0][2]
// arr[1][0] arr[1][1] arr[1][2]
// arr[2][0] arr[2][1] arr[2][2]

Answer 1

function winner(arr) {
  let circle = 0;
  let cross = 0;
  for (let i = 0; i < arr.length; i++) {
    for (j = 0; j < arr[i].length; j++) {
      if (arr[i][j] === "O") {
        circle += 1;
      } else if (arr[i][j] === "X") {
        cross += 1;
      }
    }
  }
  if (circle >= 5) {
    return "O";
  } else if (cross >= 5) {
    return "X";
  } else return "draw";
}

console.log(
  winner([
    ["O", "O", "X"],
    ["O", "O", "X"],
    ["X", "X", ""],
  ])
);

Answer 2

function winner(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][0] === arr[i][1] && arr[i][1] === arr[i][2]) {
      return arr[i][0];
    }
  }

  for (let i = 0; i < arr.length; i++) {
    if (arr[0][i] === arr[1][i] && arr[1][i] === arr[2][i]) {
      return arr[0][i];
    }
  }

  if (arr[0][0] === arr[1][1] && arr[1][1] === arr[2][2]) {
    return arr[0][0];
  }

  if (arr[2][0] === arr[1][1] && arr[1][1] === arr[0][2]) {
    return arr[2][0];
  }

  return "draw";
}

console.log(
  winner([
    ["O", "O", "X"],
    ["O", "X", "X"],
    ["O", "X", "O"],
  ])
);

console.log(
  winner([
    ["O", "O", "X"],
    ["O", "X", "X"],
    ["X", "X", "O"],
  ])
);

console.log(
  winner([
    ["O", "O", "X"],
    ["O", "O", "X"],
    ["X", "X", ""],
  ])
);









Related Posts

F2E合作社|清單群組|Bootstrap 5網頁框架開發入門

F2E合作社|清單群組|Bootstrap 5網頁框架開發入門

[ js 筆記 ] 什麼是 hoisting?

[ js 筆記 ] 什麼是 hoisting?

搞烏龍但是意外吃到美食的一天

搞烏龍但是意外吃到美食的一天


Comments