Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
How to detect Tic Tac Toe winner in Javascript with 3 child array?

I am a beginner and I want to make a Tic Tac Toe game. I want to make a function to find the winner of the game and return "x" if x win, "o" if o win, "draw" if no one win and "error" if there are two winner.

function winner(x){
  //x is an array that includes 3 child arrays, every child represents a row of tic tac toe matrix
  // example x =[["x","o","x"],["o","x","o"],["o","o","x"]]
  // It should return "x" because "x" player is the winner
}

I tried many ways but I still can't do it. Can you help me?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I am assuming that the values can also be "" apart from "x" or "o" (in case of early end to the game). Also, in case where there is no winner and the game still has some empty values, then I think it is best to return "incomplete".

function winner(x) {
  console.log(`${x[0].join(' ')}\n${x[1].join(' ')}\n${x[2].join(' ')}`);

  winners = new Set();

  // columns check
  for (let i = 0; i < 3; i++) {
    if (x[0][i] !== "" && (new Set([x[0][i], x[1][i], x[2][i]])).size === 1) {
      winners.add(x[0][i]);
    }
  }

  // rows check
  for (let i = 0; i < 3; i++) {
    if (x[i][0] !== "" && (new Set(x[i])).size === 1) {
      winners.add(x[i][0]);
    }
  }

  // diagonals check
  if (x[1][1] !== "" && ((new Set([x[0][0], x[1][1], x[2][2]])).size === 1 || (new Set([x[0][2], x[1][1], x[2][0]])).size === 1)) {
    winners.add(x[1][1]);
  }

  if (winners.size === 2) {
    return "error";
  }

  if (winners.size === 0) {
    // completion check
    if (x.every(y => y.every(z => z))){
      return "draw";
    }

    return "incomplete";
  }

  return winners.values().next().value;
}

Explanation

You see a lot of Set objects created and manipulated in the code. Set in Javascript is an easy way to ensure that there are no duplicates. They are also used in the code to check if everything passed to it is the same.

Lastly, getting the value in the Set is done in the last line.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda