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

233
Visualizações
How to reduce overly-redundant for loops

I am currently developing a Chess game and ran into a problem with code redundancy in my Bishop class. I am trying to create a function that will get all possible moves of a bishop. To do that, I would create a for loop that evaluates all diagonals of the bishop, and break the loop when it hits the end of the board or a piece. The problem with this code is it is redundant, since to evaluate all diagonals a Bishop can go, I must have 4 for loops. A simplified version of the code looks like this

var list = [1,0,0,0,1,0,0,1]; // 1d list
var index = 5; // position of "bishop"
for (let i = index, j = list.length; i < j; i++) {
    if (list[i] === 1) { // if true, return instance of 1 and break loop
        console.log("first instance of 1 going right, found at " + i);
        break;
    }
}
for (let i = index; i >= 0; i--) {
    if (list[i] === 1) { // if true, return instance of 1 and break loop
        console.log("first instance of 1 going left, found at " + i);
        break;
    }
}

Though this code works, when dealing with a bishop that can move in 4 directions, this is pretty repetitive and can lead to issues in the future. Is there a way that I am able to reduce the 4 for loops (or 2 in the example above) down to 1 without the cost of efficiency? Because the answer requires the correct concept, there isn't much to show my attempts at this problem.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would recommend using a function to replace the loops. This makes it so the same loop can be re-used without copy-pasting it.

Here is a code sample:

// Board width and height.
const boardSize = 8;
// The chess board (2d array, x index first).
const board = [[0,0,1, ...],[1,0,1, ...], ...];

// Get the maximum distance a piece can travel in a direction.
function findTravelDistance(x,y,dirX,dirY) {
    for (let n = 0;; n++) {
        // Calculate the position from moving n spaces.
        var newX = x + n*dirX,
            newY = y + n*dirY;

        // Return if the piece is off the board.
        if (newX < 0 || newX >= boardSize || newY < 0 || newY >= boardSize)
            return n - 1;

        // Return if the piece hits a one.
        if (board[newX][newY] === 1)
            return n;
    }
}

// Array containing all directions a bishop can move.
const bishopDirections = [[1,1], [1,-1], [-1,1], [-1,-1]];

// Take x and y as starting position.
// Return an array of distances corresponding to directions in bishopDirections
function findBishopTravelDistances(x,y) {
    var distances = [0,0,0,0];
    // Calculate distances for all directions.
    for (let i = 0; i < bishopDirections.length; i++)
        distances[i] = findTravelDistance()
    return distances;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

How about a left and right iterator to combine both loops and look both directions at the same time.

var list = [1,0,0,0,1,0,0,1];
var index = 5;
var left = index - 1;
var right = index + 1;
while(left >= 0 || right < list.length)
{
  if(list[left] === 1) {
    console.log("first instance of 1 going left, found at " + left);
    break;
  }

  if(list[right] === 1) {
    console.log("first instance of 1 going right, found at " + right);
    break;
  }

  if(left >= 0)
    left--;

  if(right < list.length)
    right++;
}
about 4 years ago · Juan Pablo Isaza Relatório
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