Whenever I make a move in the Towers of Hanoi javascript game, I always ensure that both towers are updated simultaneously

As I explore the Towers of Hanoi puzzle using JavaScript constructors and prototypes, I encounter issues with my current implementation. Whenever I move a disc from one tower to another, an unintended duplicate appears in a different tower. Additionally, attempting an invalid move results in the disc disappearing from its original location. Despite reviewing my logic extensively, I struggle to identify the root cause of these problems. Could it be an error within my constructor function or any of the methods?

Below is the code snippet:

function TowersOfHanoi(numberOfTowers){
   let towersQuant = numberOfTowers || 3 , towers;
   towers = Array(towersQuant).fill([]); 
   towers[0] =  Array(towersQuant).fill(towersQuant).map((discNumber, idx) => discNumber - idx);
   this.towers = towers;
}

TowersOfHanoi.prototype.displayTowers = function(){
    return this.towers; 
}


TowersOfHanoi.prototype.moveDisc = function(fromTower,toTower){
    let disc = this.towers[fromTower].pop();
    if(this.isValidMove(disc,toTower)){
       this.towers[toTower].push(disc); 
       return 'disc moved!'
    } else {
        return 'disc couldn\'t be moved.'
    }
}

TowersOfHanoi.prototype.isValidMove = function(disc,toTower){
    if(this.towers[toTower][toTower.length-1] > disc || this.towers[toTower].length === 0){
        return true; 
    }else {
        return false;  
    }
}

I'm currently testing the following:

let game2 = new TowersOfHanoi();
console.log(game2.displayTowers());  
console.log(game2.moveDisc(0,1));  
console.log(game2.displayTowers());  
console.log(game2.moveDisc(0, 2));
console.log(game2.displayTowers()); 

Here's the resulting output:

[ [ 3, 2, 1 ], [], [] ]
disc moved!
[ [ 3, 2 ], [ 1 ], [ 1 ] ]
disc couldn't be moved.
[ [ 3 ], [ 1 ],[ 1 ] ]

Any insights would be greatly appreciated as I seek to understand and resolve these issues. Thank you.

Answer №1

This excerpt from the Array fill() method's documentation highlights a common issue:

When using fill with an object, it copies the reference and populates the array with references to that same object.

towers = Array(towersQuant).fill([]); 

Arrays are treated as objects in JavaScript. This means that by filling one array with empty arrays, you're essentially creating multiple references pointing to the same original array. When you try to modify them through iteration, you encounter unexpected behavior.

Update: A revised approach that avoids this pitfall is shown below:

function TowersOfHanoi(numberOfTowers){
   let towersQuant = numberOfTowers || 3 , towers = [];
   for(let i=1; i < towersQuant; i++){
     towers.push([]);
     towers[0].push(i);
   }
  towers[0].reverse();
  this.towers = towers;
}

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

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

Sending the results from a Vue.js component to a text input field in HTML

Using vue.js and the v-for function to read QR codes has been a challenge for me. For example: <ul v-for="(scan,key) in scans" :key="key" > {{scan.content}} </ul> I need to extract the value inside {{scan.content}}, like an EmployeeID, but I ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Transferring information in React from a child component to its parent and then to another child

I'm currently developing my app using react.js and facing an issue with passing data between components. I have a Parent component (P) that needs to receive an array of objects from its child component (C1), then pass this data on to another child com ...

What exactly is the functionality of the jQuery.on() method?

I am curious about the functionality of this function and how it operates. Does it follow these steps: Identify element(s) using their selectors Assign event-handlers to them Execute a setInterval on that selector, consistently delegating and then undeleg ...

Utilizing ReactJs refs to set focus on an input element

Exploring the use of refs in ReactJs to focus a textbox from a button click. Encountering the following error message: bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined Check out the Source Code below: class FocusTex ...

Adjusting the size of div content without changing its dimensions

I'm in search of a solution for resizing the contents within a fixed width and height div. Currently, my div looks like this: <div id="editor_preview" style="width:360px !important; color:gray; ...

Invoke a component and initiate a click event from within the App.vue component

Within my template, there is a click event: <span v-on:click="showGalery()"> This event is linked to the following method: export default { name: 'osaka', data: function () { return { galery: false, } }, methods: { ...

Fetching a Wikipedia page using AJAX or the fetch() method

I am currently attempting to dynamically retrieve a Wikipedia webpage within the browser in order to utilize XSLTProcessor for further processing of the XHTML content. Unfortunately, my efforts have been unsuccessful as Wikipedia is not sending the necess ...

A guide to retrieving all image URLs when a checkbox is selected using Javascript

My goal is to extract only image URLs from the concatenated values of price and picture URL. However, when I check different images using checkboxes, it always displays the URL of the first selected image. When I try to split the value, all the prices and ...

When representing audio as sound bars on a canvas, the previous drawing is retained if canvas height is not specified

After obtaining an audioBuffer containing an audio clip, I proceed to create a visualization by drawing a series of sound bars in the shape of a circle: const { audioContext, analyser } = this.getAudioContext(); const source = audioContext.createBufferSou ...

A JavaScript or CSS file within an HTML document

I understand this may seem like a silly question. However, out of curiosity, is there a way to upload an HTML file (with a .html extension) as a JavaScript or CSS file (renamed with a .js or .css extension), specifying the type header as either HTML or js ...

Generate a graph showcasing the frequency of character occurrences within a specific column of a .csv file

I'm currently working on creating a graph using d3.js What I need to accomplish is reading the some_column column in a .csv file and counting the occurrences of | to plot them accordingly on the y-axis. The line should be plotted based on the number ...

Opening a Bootstrap Modal in React without relying on npm react-bootstrap

I've been trying to create a Modal in React.js using Bootstrap5, but I'm unable to use npm react-bootstrap for various reasons. I attempted an approach where I utilized state to set Modal classes with a button, which worked well with my NavBar, b ...

Transforming user-entered date/time information across timezones into a UTC timezone using Moment JS

When working on my Node.js application, I encounter a scenario where a user inputs a date, time, and timezone separately. To ensure the date is saved without any offset adjustments (making it timezone-independent), I am utilizing Moment Timezone library. ...

Invoking an AJAX function that is not inside the document.ready function

I'm having trouble populating a Google Map and here's some of the code I'm using. The ajax request doesn't seem to be working properly. When I put everything inside document.ready() as an anonymous function, it works fine. However, sinc ...

Scouring the web with Cheerio to extract various information from Twitter

Just starting out with Web Scraping, using Axios to fetch the URL and Cheerio to access the data. Trying to scrape my Twitter account for the number of followers by inspecting the element holding that info, but not getting any results. Attempting to exec ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Troubleshooting a Malfunctioning AJAX Request in a WordPress Plugin

After carefully reviewing this post about a jQuery Ajax call in a Wordpress plugin page, I found that it closely matched my current issue. My basic Wordpress plugin is designed to offer a specific membership form that passes payment details to PayPal for p ...