Tips for minimizing excessive repetition in your for loops

I'm currently working on developing a Chess game and I've encountered an issue with code redundancy within my Bishop class. My goal is to create a function that can determine all possible moves of a bishop on the board. In order to achieve this, I would need to use a for loop to evaluate all diagonals that the bishop can traverse, stopping when it reaches the edge of the board or encounters another piece. The problem with my current approach is that it requires multiple for loops (4 in total) to assess all possible directions the Bishop can move.

const list = [1, 0, 0, 0, 1, 0, 0, 1]; // 1D array
const index = 5; // Bishop's position
for (let i = index; i < list.length; i++) {
    if (list[i] === 1) { 
        console.log("First instance of 1 found going right at index: " + i);
        break;
    }
}
for (let i = index; i >= 0; i--) {
    if (list[i] === 1) { 
        console.log("First instance of 1 found going left at index: " + i);
        break;
    }
}

While the current code works, having to use multiple for loops becomes repetitive and may pose challenges in the future, especially considering the Bishop can move in four different directions. Is there a way to consolidate these multiple loops into a single one without sacrificing efficiency? As finding the solution hinges on understanding the correct concept, I haven't made any specific attempts at solving this issue yet.

Answer №1

If you're looking to streamline your code and avoid repetitive loops, consider implementing a function for efficiency. With this approach, you can easily reuse the same loop without the need for copying and pasting it multiple times.

Check out this code snippet below:

// Defining board dimensions.
const boardSize = 8;
// Chessboard represented as a 2D array (x index first).
const board = [[0,0,1, ...],[1,0,1, ...], ...];

// Function to determine the maximum piece travel distance in a given direction.
function findTravelDistance(x,y,dirX,dirY) {
    for (let n = 0;; n++) {
        // Calculate new position after moving n steps.
        var newX = x + n*dirX,
            newY = y + n*dirY;

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

        // Return if the piece encounters another piece.
        if (board[newX][newY] === 1)
            return n;
    }
}

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

// Input starting position (x,y) and output distances for bishop movement directions.
function findBishopTravelDistances(x,y) {
    var distances = [0,0,0,0];
    // Compute distances for each direction.
    for (let i = 0; i < bishopDirections.length; i++)
        distances[i] = findTravelDistance()
    return distances;
}

Answer №2

How about creating a left and right iterator to simultaneously scan in both directions?

let numbers = [1, 0, 0, 0, 1, 0, 0, 1];
let position = 5;
let leftIndex = position - 1;
let rightIndex = position + 1;

while (leftIndex >= 0 || rightIndex < numbers.length) {
    if (numbers[leftIndex] === 1) {
        console.log("First instance of 1 found when going left, at position: " + leftIndex);
        break;
    }

    if (numbers[rightIndex] === 1) {
        console.log("First instance of 1 found when going right, at position: " + rightIndex);
        break;
    }

    if (leftIndex >= 0)
        leftIndex--;

    if (rightIndex < numbers.length)
        rightIndex++;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...

Setting the font-size in HTML/CSS to dynamically adjust and fill the entire width and height of its

I'm trying to make a <div> element adjust its size based on the browser window. Within this <div>, there is a paragraph of text: <div style="width:80%; height:80%; margin:10%;"> <p>Paragraph of text. Paragraph of text. Pa ...

activate a single on.click event to trigger additional actions - utilizing javascript and jQuery

My website features dynamically generated buttons that lead to specific pages. The challenge I'm facing is retrieving the automatically generated data-num value for each button and using it as a jQuery selector to redirect users to the corresponding p ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Creating a Self Closing Alert Message in AngularJS: A Step-by-Step Guide

Just getting started with AngularJS and looking to create a self-closing message. How can this be accomplished? I'm aiming for similar results as the question found here: How to Automatically Close Alerts using Twitter Bootstrap However, I want to ...

Adjust the text color based on the background image or color

Here on this site, I have designed the first div to display a dark image, while the second one shows a light background. I am aiming to adjust the sidebar text color based on whether it is displayed against the dark or light background. How can I achieve ...

Using JQuery to cycle a class with a timer

My list has the following structure <div id="slider"> <ul> <li class='active'> a </li> <li> b </li> <li> c </li> <li> d </li> <li> e </li> </u ...

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

Issue with Material UI components: The Select component is collapsed and the autoWidth functionality is not

The Material UI (React) Select component is not expanding in width as expected, even with the autoWidth property. https://i.sstatic.net/h3H0V.png <FormControl margin="dense"> <InputLabel id="prefix-label">Prefi ...

When attempting to push `content[i]` into an array in AngularJS, it is flagged

In my JSON data, I have the following structure: var data = [{ id: 1, name: 'mobile', parentid: 0, limit:3 }, { id: 2, name: 'samsung', parentid: 1 }, { id: 3, name: 'moto', parenti ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Changing route parameters or query parameters does not trigger a reload of component data in React

The "home" component has links that direct to the product component when clicked. Another component always visible displays links to recently visited products. However, on a product page, these links fail to work properly. Although the URL updates and tri ...

Ways to stop your Browser from Caching

Developing a Facebook app has been my recent project. One thing that really bothers me is the random occurrences where changes I make to my CSS style sheet or when adding a new Javascript function do not reflect in the browser. This can be very frustrating ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

Display and conceal elements within predetermined time intervals using jQuery, while ensuring that the final element remains visible

Is there a way to automatically hide div1 and show div2 after a set amount of time, let's say 10 seconds or 15 seconds? I came across this thread: Show and hide divs at a specific time interval using jQuery, However, the solution provided in the po ...

Guide on exporting a dynamically imported class instance using ES6 modules in NodeJS

Currently, I am engrossed in a book on NodeJS that illustrates a simple web application example. In this example, the prerequisite is to have various data store classes housed in their respective modules and dynamically selecting the data store by configur ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...

Send functions from the back-end Node to the front-end Angular

Introduction I am currently working on a project that involves verifying email addresses within an API in order to grant users access to a restricted section. To accomplish this, I have developed backend node code with three functions built using Node and ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...