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

先從變數開始談起

先從變數開始談起

Fetch 與 Promise (二):錯誤處理

Fetch 與 Promise (二):錯誤處理

如何使用 K8S 自動化定期 CronJob 抓網路公開資料

如何使用 K8S 自動化定期 CronJob 抓網路公開資料


Comments