Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Avoiding nested loops in a TicTacToe algorithm JavaScript

I wrote a quick algorithm that detects a win in a TicTacToe Game.

function game() loops through a simulated ticTacToe board, finds all the index's of a given value, then loops through all the possible winning combos, finds any index's where the actual value is equal to the index's from the first loop, (I know :/) then replaces the value with the value passed into the function (either x or o).

Then, a subsequent function is run that checks if every value inside any of the nested arrays inside the possibleWinCombos are all equal to each other. If true, a winner is found.

const possibleWinCombos = [
  [0, 1, 2], //================ //
  [3, 4, 5],  //== Horizontal == //
  [6, 7, 8],  //=================//

  [0, 3, 6],  //================ //
  [1, 4, 7],  //== Vertical == //
  [2, 5, 8],  //=================//
  
  [0, 4, 8],  //=================//
  [2, 4, 6],  //== Diagonal == //
]

const ticTacToe = [
  'x', 'o', null,
  null, 'x', null,
  'o', null, 'x',
]

const game = (value) => {
  ticTacToe.forEach((cell, idxOfCell) => {
    if(cell === value){
      for (winCombo of possibleWinCombos){
        let idxToReplace = winCombo.indexOf(idxOfCell) 
        winCombo.splice(idxToReplace, 1, value)
      }     
    }
  })
  
  checkForWinner(value) ? 
    console.log(`${value}'s win`) : console.log('game still going')
}

const checkForWinner = (value) => {
  return possibleWinCombos.some((winCombo) => {
    return winCombo.every((winComboValue) => winComboValue === value);
  })  
}

game('x') // x's win
game('o') // game still going

It's only two functions so it's not very code heavy but I feel like game() wouldn't score very high on the performance rankings due to the nested looping. Any recommendations on some improvements would be great.

https://replit.com/@uwitdat/DrabNoteworthyLogin#script.js

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda