0
   

recursive function in JavaScript

 
 
Reply Sat 17 May, 2014 08:48 pm
I got stack overflow just after the line else{ when calling this function throught a button onclick, does any one know why? thanx
function Hanoi_Tower()
{

var fromPeg ='A';
var toPeg ='B';
var auxPeg ='C';
var n=3;

if (n==1) {
document.write('Move ring no.1 form Peg '+ fromPeg + ' to Peg ' + toPeg);
}

else {

Hanoi_Tower(fromPeg,auxPeg , toPeg,n-1);
document.write('Move ring no. ' + n + ' from ' + fromPeg + ' to ' + toPeg);
Hanoi_Tower(auxPeg,toPeg ,auxPeg,n-1);

}

}
  • Topic Stats
  • Top Replies
  • Link to this Topic
Type: Question • Score: 0 • Views: 624 • Replies: 1
No top replies

 
samy youssef
 
  1  
Reply Wed 21 May, 2014 05:32 am
@samy youssef,
Finally I did it, it works with Hanoi Tower puzzle, this puzzle for those who never heard of is to move a number of rings different in size(diameters) from say a beginning peg to a final peg with the aid of an aux peg, conditions: move one ring at a time, and never put a big ring over a smaller one :

pleased if someone try it and say any improving suggestions as how to make
=====================================================
this code move the rings actually, I mean with images
=====================================

<script>
function Hanoi_puzzle()
{
alert('Thank God it worked!');
var i=prompt('Enter a number',0);
if (isNaN(i) || i>10) // stack overflow might occur if otherwise
{
alert('Wrong Entry');
stop();
}
i=Math.round(i); // to round up the number if entered as float

var myPuzzle = function Hanoi_Tower(fromPeg,toPeg,auxPeg,n)
{

if (n==1) {
document.write('Move ring no.1 form Peg '+ fromPeg + ' to Peg ' + toPeg);
document.write('<br />');
}

else {

Hanoi_Tower(fromPeg,auxPeg , toPeg,n-1);
document.write('Move ring no.' + n + ' from Peg ' + fromPeg + ' to Peg ' + toPeg);
document.write('<br />');
Hanoi_Tower(auxPeg,toPeg ,fromPeg,n-1);

}

}
var x = Math.pow(2,i);
var moves=x-1
myPuzzle('A','C','B',i);
alert('Total number of Rings are: ' + i + ' Total Moves = ' + moves);
document.write('Total umber of Rings are: ' + i + ' Total Moves = ' + moves);
}
</script>
<body>
<button onclick =Hanoi_puzzle()>Hanoi Tower </button>
</body>
0 Replies
 
 

Related Topics

 
  1. Forums
  2. » recursive function in JavaScript
Copyright © 2024 MadLab, LLC :: Terms of Service :: Privacy Policy :: Page generated in 0.03 seconds on 05/16/2024 at 11:05:23