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.