A recursive function stuck in an endless loop, going on indefinitely

I have a recursive function that is supposed to call itself until the coordinates exceed the boundaries of a DOM table or until the distance between the starting point and the current recursion point is greater than the user-defined distance. However, the function seems to be stuck in an infinite loop, constantly switching between several points and I can't seem to pinpoint what went wrong.

function fillSquare(a,b,dist){
    var xStart = parseInt(a);
    var yStart = parseInt(b);
    var distance = dist;

    function fill(c,d){
        var x = parseInt(c);
        var y = parseInt(d);

        if(x<span class="operator"><</span>0 || y<span class="operator"><</span>0 || x<span class="operator">></span>boardWidth-1 || y<span class="operator">></span>boardHeight-1){
            return;
        }else if(getDistance(cells[getFieldId(xStart,yStart)], cells[getFieldId(x,y)]) <span class="operator">></span> dist){
            return;
        }else{
            cells[getFieldId(x,y)].hasWall = false;
            document.getElementById(x+'x'+y).backgroundColor = 'gray';
            console.log(x+' '+y);

            fill(x-1,y);
            fill(x+1,y);
            fill(x,y-1);
            fill(x,y+1);
        }
    }

    fill(xStart,yStart);
}

Any assistance on this matter would be highly appreciated.

Answer №1

The issue arises from the recursive calls repeatedly returning to the same elements. For example, a call to fill(4, 5) leads to fill(3, 5), then fill(4, 5) again, creating an endless loop between them.

To resolve this problem, it is important to implement a check to see if an element has already been filled to prevent repetition.

function fill(c,d){
    var x = parseInt(c);
    var y = parseInt(d);

    if(cells[getFieldId(x, y)].hasWall === false || x<0 || y<0 || x>boardWidth-1 || y>boardHeight-1){
        return;
    }else if(getDistance(cells[getFieldId(xStart,yStart)], cells[getFieldId(x,y)]) > dist){
        return;
    }else{
        cells[getFieldId(x,y)].hasWall = false;
        document.getElementById(x+'x'+y).backgroundColor = 'gray';
        console.log(x+' '+y);

        fill(x-1,y);
        fill(x+1,y);
        fill(x,y-1);
        fill(x,y+1);
    }
}

Answer №2

Unfortunately, without access to the remaining code, could you please provide the console output for the following:

// Debugging purposes
var i = 0;

// Helper function for converting into integers
function fillSquare(xStart, yStart, distance)
{
    // Initialization
    // The first run uses start as current
    fill(parseInt(xStart), parseInt(yStart), parseInt(xStart), parseInt(yStart), distance);
}

function fill(xCurrent, yCurrent, xStart, yStart, distance)
{
    // The next two lines are temporary for debugging only
    ++i;
    if(i > 100) return;

    // Logging current progress
    console.log({ "xCurrent" : xCurrent, "yCurrent" : yCurrent, "xStart" : xStart, "yStart" : yStart, "distance" : distance, "getDistance" : getDistance(cells[getFieldId(xStart,yStart)], cells[getFieldId(xCurrent, yCurrent)]) });

    // No need to parse again since it was done in the initial run and the recursive calls rely on basic math

    if(xCurrent < 0 || yCurrent < 0 || xCurrent > boardWidth - 1 || yCurrent > boardHeight - 1)
    {
        return;
    }
    else if(getDistance(cells[getFieldId(xStart,yStart)], cells[getFieldId(xCurrent, yCurrent)]) > distance)
    {
        return;
    }
    else
    {
        cells[getFieldId(xCurrent,yCurrent)].hasWall = false;
        document.getElementById(xCurrent + 'x' + yCurrent).backgroundColor = 'gray';

        fill(xCurrent - 1, yCurrent, xStart, yStart, distance)
        fill(xCurrent + 1, yCurrent, xStart, yStart, distance)
        fill(xCurrent, yCurrent - 1, xStart, yStart, distance)
        fill(xCurrent, yCurrent + 1, xStart, yStart, distance)
    }
}

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

Leverage the variables' values to access property

There is a way to use this possibility: let eventSelected = "333"; let bestResult = result.personal_records[eventSelected]?.single?.best //like searching like this: result.personal_records.333?.single?.best However, when deali ...

Emphasize the cell in the initial column to indicate the resulting or winning selection

Having trouble sharing my code directly, so please check out the JSFiddle link to see it in action. Once you click the "Click to Draw a Winner" button, a winner will be randomly selected after 10 seconds. The only issue is that currently only the winning b ...

Establishing the variable for the input value attribute with a space included

I am facing an issue with setting the value of an input button to a string variable, specifically "A Guide to the School Bus." When the HTML loads, only the first word shows up on the button. Below is my code. Any help would be appreciated. var title = "A ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...

Adjust the hue of a single side of the cube with THREE.js

I'm currently delving into the world of OOP with Three.js, which is proving to be quite challenging. To start, I decided to create a box within the scene. Now, my next goal is to change the color of one face of that cube. var scene = new THREE.Scene( ...

The CSS I've written isn't functioning properly within a div that was generated using

I have been trying to populate a div with data using JSON, but I am facing an issue where my div, which is set with JavaScript for each JSON element, does not seem to be working correctly. The classes "lulu" and "lora" are not being recognized. Apologies f ...

Is there a way for me to enable autoplay on the Slice Slider?

I'm struggling to enable autoplay on a slider I have here. Is it possible to quickly set this up in the var settings? I attempted to insert the setInterval(spin, 3000); command before and after the init lines, but it hasn't been successful so fa ...

jQuery Autocomplete with Link Options

Can anyone help me with creating a search function for my charity's internal website? I've managed to get it partially working, but I'm struggling to make the results link to the right places. Below is the code I have so far, including test ...

Vue.js error: Trying to access an undefined property

Here is my Vue instance setup: const vueApp = new Vue({ el: '#vue-wrapper', data: { items: [] }}); Utilizing a v-for loop in index.html.eex: <div v-for="item in items[0].subItems">{{ item.name }}</div> In this scri ...

What is the process of converting an arrow function into an asynchronous one?

In the code snippet below, I am checking for the existence of a file and if it is present, I am parsing the JSON data from it: fs.access(dbPath, (err) => { if (err) throw err else{ console.log('Database found. Processin ...

Modify the filtered class of ng-repeat using the $index value from the controller

Here is my ng-repeat code: <div class="{{event.who_seen_it | newEvent}}" ng-repeat="event in eventList" ng-click="openEvet(event.title,$index)"> <h3 class="event-title">{{event.title}}</h3> </div> I am using the {{event.who_se ...

The JavaScript function prints the variable using `console.log(var)`, however, it does not assign `var2` to

I've been following a tutorial on implementing push notifications in VueJS from this link. After running the register function on the created hook, I encountered an issue: register() { if ("serviceWorker" in navigator && "PushManager" in window ...

Guide to loading JQuery in an electron webview using a proxy

Currently, I am configuring an electron application with an index.html file that includes a webview. The webview has a reverse proxy connected to it which modifies all "/" routes. Due to this setup, I am unable to load CDN libraries such as JQUERY within t ...

Transform a String into an Array object

There is a string that resembles the following pattern: var stringArray = "[[1,2,3,4],[5,6,7,8]]" The objective is to use Javascript to convert it to the following format: var actualArray = [[1,2,3,4],[5,6,7,8]] What would be the method to accomplish ...

Exploring Angular.js methods to capture values from check boxes and radio buttons simultaneously

Check out my demo at https://embed.plnkr.co/R4mdZr/ Just diving into the world of Angular, I'm looking to retrieve both true values from checkboxes and radio button selections. I have a condition where if the minimum value for ingredients is one, it ...

Error: Unable to access attribute 'item_name' as it is not defined

I'm new to React.js and I'm attempting to build a todo app. The main feature is a text input field where users can add items to their list. When I run "npm start," the app works perfectly and displays the expected output on my designated port. Ho ...

When the affirmative button is clicked, apply a border and background color

I am in the process of creating custom text boxes for user comments. I need help with adding borders and background colors to a box when the user clicks on the YES button, in order to visually indicate which box the click originated from. Can anyone assis ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

Creating relationships in Sequelize.js: Linking a model using two keys from another model

I have a comprehensive Users model that stores all the necessary user information for my application. // model definition for the users table module.exports = function(sequelize, DataTypes) { var User = sequelize.define("User", { email: { ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...