Question

Need Help correcting last function runHanoi(A,C,B) so this program correctly calculates number of...

Need Help correcting last function runHanoi(A,C,B) so this program correctly calculates number of moves made. Solving the Hanoi tower. Please post correct Javascript. This is used in jsfiddle.

HTML:

html>
<schript src="TowerOfHanoi.js"</script>
</script>
<h1>
Tower of Hanoi
</h1>
Enter the number of disks (Disk amount must be < 7): <br>
<br>
<input id = 'uInput' type = 'textbox' size = 10 >
<button id = 'setup' onClick = 'insertDisks()'>
Set up Tower of Hanoi
</button>
<button id=calc onClick = 'runHanoi(stackA, stackC, stackB)'> Calculate number of moves
</button>

<br> <br>
<button id = 'aTob' onClick = 'aTob()'>A to B</button>
<button id = 'aToc' onClick = 'aToc()'>A to C</button>
<button id = 'bToa' onClick = 'bToa()'>B to A</button>
<button id = 'bToc' onClick = 'bToc()'>B to C</button>
<button id = 'cToa' onClick = 'cToa()'>C to A</button>
<button id = 'cTob' onClick = 'cTob()'>C to B</button>
<br><br>

<div id = 'output'>
</div>
<div id = 'output1'>
</div>
</html>

JS:

var num = 0;
var t = document.getElementById('uInput').value;

var Node = function(_content) {
this.content = _content;
this.next = null;
this.last = null;
return this;
}

var Stack = function(_content) {
this.top = null;
this.bottom = null;
this.length = 0;
return this;
}

Stack.prototype.push = function(_content) {

var node = new Node(_content);
node.content = _content;

if (this.bottom == null) {
this.bottom = node;
this.top = this.bottom;
this.length++;
return this;
}

node.last = this.top;
this.top.next = node;
this.top = node;
this.length++;
return this;
}

Stack.prototype.pop = function() {
if (this.bottom == null) {
alert('Stack is empty.');
return false;
}

if (this.bottom == this.top) {
this.bottom = null;
this.top = null;
this.length = 0;
return this.top
}

var popped = this.top;
this.top = this.top.last;
this.top.next = null;
this.length--;
return popped;
}

Stack.prototype.toString = function() {
var string = '';
var n = this.bottom;

while (n != null) {
string += n.content ;
n = n.next;
}
return string;
}

Stack.prototype.reverse = function(str) {
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
}

function insertDisks(i) {
i = parseInt(document.getElementById('uInput').value);
if (i > 7) {
alert('Input must only be less than 7');
document.getElementById('uInput').value = '';
document.getElementById('uInput').focus();
return false;
}
for (var t = i; t > 0 ; t--) {
stackA.push(t);
stackA.length++;


}
document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();

}

var stackA = new Stack();
var stackB = new Stack();
var stackC = new Stack();

function aTob() {
var n = parseInt(stackA.top.content);
stackA.pop(n);
stackB.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackB.reverse(n);
}


function aToc() {
var n = parseInt(stackA.top.content);
stackA.pop(n);
stackC.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackC.reverse(n);
}


function bToa(){
var n = parseInt(stackB.top.content);
stackB.pop(n);
stackA.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackA.reverse(n);
}

function bToc(){
var n = parseInt(stackB.top.content);
stackB.pop(n);
stackC.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackC.reverse(n);
}


function cToa(){
var n = parseInt(stackC.top.content);
stackC.pop(n);
stackA.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackA.reverse(n);
}


function cTob(){
var n = parseInt(stackC.top.content);
stackC.pop(n);
stackB.push(n);

document.getElementById('output').innerHTML = 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
stackB.reverse(n);
}

function runHanoi(A, C, B) {
var c = stackA.length;
//alert(c);
if (c >= 1) {
runHanoi(c-1, A, B, C);
C.push(A.pop().content);   
num++;
runHanoi(c-1, B, C, A);
document.getElementById('output1').innerHTML += 'Towers: Stack A :' + stackA.toString() + '_Stack B: ' + stackB.toString() +'_Stack C: ' + stackC.toString();
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

It is better to replace your code with the below code for error free and better results.

JS code to implement the Towers of Hanoi problem:

import Stack from '../../../data-structures/stack/Stack';

/* Variables used in a program:
* {number} numberOfDiscs
* {Stack} fromPole
* {Stack} withPole
* {Stack} toPole
* {function(disc: number, fromPole: number[], toPole: number[])} moveCallback
*/
function hanoiTowerRecursive({
numberOfDiscs,
fromPole,
withPole,
toPole,
moveCallback,
}) {
if (numberOfDiscs === 1) {
// Base case with just one disc.
moveCallback(fromPole.peek(), fromPole.toArray(), toPole.toArray());
const disc = fromPole.pop();
toPole.push(disc);
} else {
// In case if there are more discs then move them recursively.

// Expose the bottom disc on fromPole stack.
hanoiTowerRecursive({
numberOfDiscs: numberOfDiscs - 1,
fromPole,
withPole: toPole,
toPole: withPole,
moveCallback,
});

// Move the disc that was exposed to its final destination.
hanoiTowerRecursive({
numberOfDiscs: 1,
fromPole,
withPole,
toPole,
moveCallback,
});

// Move temporary tower from auxiliary pole to its final destination.
hanoiTowerRecursive({
numberOfDiscs: numberOfDiscs - 1,
fromPole: withPole,
withPole: fromPole,
toPole,
moveCallback,
});
}
}

/* Variables used in a program:
* {number} numberOfDiscs
* {function(disc: number, fromPole: number[], toPole: number[])} moveCallback
* {Stack} [fromPole]
* {Stack} [withPole]
* {Stack} [toPole]
*/
export default function hanoiTower({
numberOfDiscs,
moveCallback,
fromPole = new Stack(),
withPole = new Stack(),
toPole = new Stack(),
}) {
// Each of three poles of Tower of Hanoi puzzle is represented as a stack
// that might contain elements (discs). Each disc is represented as a number.
// Larger discs have bigger number equivalent.

// Let's create the discs and put them to the fromPole.
for (let discSize = numberOfDiscs; discSize > 0; discSize -= 1) {
fromPole.push(discSize);
}

hanoiTowerRecursive({
numberOfDiscs,
fromPole,
withPole,
toPole,
moveCallback,
});
}

Add a comment
Know the answer?
Add Answer to:
Need Help correcting last function runHanoi(A,C,B) so this program correctly calculates number of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have the code buts its not working as this below instruction can anyone help Use...

    I have the code buts its not working as this below instruction can anyone help Use the requirements from the pizza part of Assignment 6 and do the following using CSS and an internal style sheet: 1.     Your Javascript function should be in an external file (don’t forget to move it up to studentweb too) 2.     Put a red border of 300px in width around the form 3.     There should be three Div sections: header, main_body, and footer. 4.     Center the name of your...

  • Please advise what is being doing wrong. Requirement. See if you can modify the code of...

    Please advise what is being doing wrong. Requirement. See if you can modify the code of Listings 17.1 and 17.3 to present a message to the user while waiting for an Ajax request to complete. //Code <!DOCTYPE html> <html> <head> <title>Keywords Grabber</title> <script src="myAjaxLib.js"></script> <script> function display(content) { document.getElementById("displaydiv").innerHTML = content; </script> <script> function getXMLHttpRequest() { try { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { return new ActiveXObject("Msxml2.XMLHTTP"); } } catch(e) { return new XMLHttpRequest(); } } function doAjax(url,...

  • Modify this code to store the form elements as variables and display them on the page...

    Modify this code to store the form elements as variables and display them on the page in an HTML table. <!DOCTYPE html> <html> <head> <script> function getValues() {     var result = ""; result += "First Name: " + document.forms["myForm"]["fname"].value + "<br>"; result += "Last Name: " + document.forms["myForm"]["lname"].value + "<br>"; result += "Address: " + document.forms["myForm"]["address"].value + "<br>"; result += "City: " + document.forms["myForm"]["city"].value + "<br>"; result += "State: " + document.forms["myForm"]["state"].value + "<br>"; document.getElementById("output").innerHTML = result; } </script>...

  • I have some code for HTML/Javascript but I need to change it up a bit. Heres...

    I have some code for HTML/Javascript but I need to change it up a bit. Heres the assignment and what I have. The part in the bold is what I need help with. I need a button called new timer for when it reaches zero... Thank you. Assignment For this assignment, you will write a timer application in HTML and JavaScript. Your HTML document should contain the following elements/features: HTML tags: An <input> tag labeled "Timer Duration" with the initial...

  • LANGUAGE JAVASCRIPT, PHP Need help with PHP and ajax code. The user needs to login but,...

    LANGUAGE JAVASCRIPT, PHP Need help with PHP and ajax code. The user needs to login but, I keep getting an error that I coded "Wrong username and password!" ***PLEASE DONT GIVE ME A NEW CODE THAT IS NOWHERE NEAR THE CODE I SUBMITTED***** PLEASE LOOK AT THE CODE AND SEE ANY ISSUES login.html <!DOCTYPE html> <html> <head> <title>login popup</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style type="text/css"> body { background-color: white; } </style> </head> <body> <center> <h1 style="text-align: center;"> Login </h1> <form>             Login ID:...

  • I need HELP to get the code to do these function: If I keep clicking "Generate"...

    I need HELP to get the code to do these function: If I keep clicking "Generate" multiple times, the list keeps on getting bigger. The number of rows should always be equal to the number of columns. Also make the code to show both table at the same time? Here is the code I got some far : Code: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Testing</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> </head> <style> td...

  • Write a html javascript program to do the following: the user inputs a number, for example,...

    Write a html javascript program to do the following: the user inputs a number, for example, 50 user presses a button, labeled START the program creates 50 random buttons around the browser window each button should be placed at a random location each button should be labeled with a random number between 1 and 50 add the following features every 2 seconds, move each button around by increment or decrementing its location if the user clicks on a button, change...

  • How to make all the buttons work using javascript? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta...

    How to make all the buttons work using javascript? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function openAccount() { /* - get the account and initial amount values - check that all necessary information is provided - call the setCookie function to create account */ } function Deposit() { /* - get the account and amount values - check that all necessary information is provided - alter cookie with current amount of deposit */ } function...

  • can you do this js and html question. ill give you the html and js and...

    can you do this js and html question. ill give you the html and js and css files just fix my error use if and else like what i did dont use switch just fix my erorr. <!DOCTYPE html> <!-- Webpage HTML document for Lab 4. Authors: Amirhossein Chinaei, Andriy Pavlovych For: EECS 1012, York University, Lassonde School of Engineering --> <html lang="En"> <head> <meta charset="UTF-8"> <!-- title for web page --> <title> EECS1012: Lab 4 - Computational Thinking </title>...

  • NEED HELP with HTML with Javascript embedding for form validation project below. I have my code...

    NEED HELP with HTML with Javascript embedding for form validation project below. I have my code below but I'm stuck with validation. If anyone can fix it, I'd really appreciate. ****************************************************************************** CODE: <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>Nice</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> var textFromTextArea; function getWords(){ var text =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT