Skip to content

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.

Answer

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;
}