HighDots Forums  

Re: Two-Dimensional Recursive JavaScript

Javascript JavaScript language (comp.lang.javascript)


Discuss Re: Two-Dimensional Recursive JavaScript in the Javascript forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Tom de Neef
 
Posts: n/a

Default Re: Two-Dimensional Recursive JavaScript - 08-14-2008 , 09:36 AM







<wgarner (AT) ucsd (DOT) edu> wrote
Quote:
I am trying to implement a two-dimensional recursive formula, g(x,y).
It is sort of like multiplication.

g(x,y) = 0 if either x or y is 0. g(1, y) = y and g(x, 1) = x.

Those are the base cases.

snip


function nim_mult(a,b) {

var g = new Array(a+1);
for(i=0; i<=a;i++) {
g[i] = new Array(b+1);
}
Every time you enter this function it will create the g array and fill it.
And the function is called recursively, so it doesn't meet your objective.
Instead, you want to declare and fill it once. That should thus happen in an
'outer' function. The recursion should than be placed in an inner function.
See later.
Quote:
for(i=0;i<=a;i++) {
g[i][0] = 0;
if(b>0)
g[i][1] = i;
}
for(j=0;j<=b;j++) {
g[0][j] = 0;
if(a>0)
g[1][j] = j;
}

I'm not sure that it is sensible to fille the elements [0,j] and [i,0]. Will
they ever be accessed ?
Quote:
if(a=="0" || b=="0") {
return 0;
} else if (a=="1") {
return b;
} else if(b=="1") {
return a;
} else {
NB: why do you compare a and b here to a string, wheras before you compared
them to numbers. The following code will achieve the same:
if (a==0 || b==0) return 0;
if (a==1) return b;
if (b==1) return a;

Quote:
nim_mult_str="";

for(i=0; i<a; i++) {
for(j=0; j<b; j++) {
nim_mult_str+= "," + nim_mult(i,b) + ",";
}
I don't understand why you loop thru j. Part of the formula is missing ?
}
g[a][b] = h(nim_mult_str);

return g[a][b];
}

I think that your idea of storing results in the 2d array could be
implemented as follows.
function nim_mult(a,b) {
if (a==0 || b==0) return 0;
if (a==1) return b;
if (b==1) return a;
var i,g = []
for (i=0;i<a;i++) {g[i] = []}; // create g and make it available to inner
function
function inner(a,b) {
var i,j,result
if (a==0 || b==0) return 0;
if (a==1) return b;
if (b==1) return a;
result=g[a][b]
if (result) return result;
result="";
for(i=0; i<a; i++) {
for(j=0; j<b; j++) {
result+="," + inner(i,b) + ","+inner(a,j); // ???
}}
g[a][b]=result;
return result
}
return inner(a,b)
}

Tom




Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.