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

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

Unable to dispatch an event from a child component to a parent component in Vue.js

Within my parent component, I retrieve an array of strings from an API and pass it down to the child component. The child component then displays this data as a dropdown list. When an item is selected from the dropdown, I aim to assign it to a specific var ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log(file); }) However, this snip ...

Concealing numerous tables depending on the visibility conditions of subordinate tables

I have the following HTML code which includes multiple parent tables, each with a specific class assigned to it: <table class="customFormTable block"> Within these parent tables, there are child tables structured like this: <table id="elementTa ...

Discover multiple keys within a new Map object

Our usual approach involves creating a new Map like this: const hash = new Map() hash.set(key,value) To retrieve the information, we simply use: hash.get(specificKey) An advantage of using Map is that we have flexibility in choosing keys and values. Cur ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

"jquery-ajax was unable to complete the request, whereas it was successfully executed using

I am currently using jQuery to trigger an ajax request. However, when I make the request using jQuery, I encounter an "Unexpected end of input" error with no response coming from the PHP file. Strangely enough, if I manually copy the request from the Chrom ...

From JSON to PNG in one simple step with Fabric.js

I am looking for a way to generate PNG thumbnails from saved stringified JSON data obtained from fabric.js. Currently, I store the JSON data in a database after saving it from the canvas. However, now I want to create a gallery of PNG thumbnails using thi ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Is it possible to customize the background color of select2 boxes separately for each option?

I recently implemented the select2 plugin and now I'm looking to add a new class within the .select2-results .select2-highlighted class in order to change the background color. Does anyone have any suggestions on how to achieve this? ...

What is the correct way to store user input in the "store" using vuex.js? Can you help me identify where I went wrong?

On the third day of my suffering, I seek your help. Can you please guide me on how to save text input in "store" in vuex.js and then add it to the value of the same input itself? I've attempted it like this but seem to be making a mistake somewhere. ...

What is the best way to successfully implement multiple post requests using Django and Ajax on a single webpage?

After spending the entire day struggling with this issue, I am still unable to make any progress. Let me explain my predicament. In my Django form, I have two fields: redirect_from and redirect_to. The form contains two buttons: Validate and Save. Initial ...

Determine if an element is being hovered over using jQuery

How do I determine if the cursor is hovering over an element using jQuery or JS? I attempted to use $('#id').is(':hover'), but it doesn't seem to be functioning as expected. It's worth mentioning that I am calling this line ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

If Gulp is running continuously, what output will I receive?

After reading a helpful post on StackOverflow about gulp tasks (viewable here), I came to the conclusion that it's not advisable to omit returning anything in a gulp task. For proper synchronization of asynchronous tasks, the caller should wait. Pres ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

JavaScript sorted arrays are an efficient way to keep data

In my dataset, I have an array of objects representing various products. Each product object includes a field called ratingReviews and another field called price, which can either be a string or an object. If the price is represented as an object, it conta ...