Convert permute method from Java to JavaScript -


i implemented java code permutation combination string input str= "word1 word2 word3" output as:

arr[0]= "word1 word2"

arr[1]= "word1 word3"

arr[2]= "word1 word2 word3"

arr[3]= "word2 word1"

arr[4]= "word2 word1 word3"

arr[5]= "word2 word3 word1"

arr[6]= "word3 word1"

arr[7]= "word3 word1 word2"

arr[8]= "word3 word2 word1"

this java code:

private static void permute(string[] ss, boolean[] used, string res, int level, list<string> list) {      if (level == ss.length && res != ""){         list.add(res);     return;     }      (int = 0; < ss.length; i++) {         // check if string used         if (used[i]) {             continue;         }         // check if res empty or single word         if(level > 1)             list.add(res);             used[i] = true;             permute(ss, used, res + " " + ss[i], level + 1, list);             used[i] = false;         }     }  public static list<string> permutewords(string s){     string[] ss = s.split(" ");     boolean[] used = new boolean[ss.length];     string res = "";     list<string> list = new arraylist<string>();     permute(ss, used, res, 0, list);     return list; } 

when converting js code, don't know errors in code:

function permute(ss, used, res, level, list){   if(level==ss.lenght&&res!==""){       list.add(res);       return;   }    for(var i=0; i<ss.lenght; i++){       if (used[i]===true){         continue;       }        if(level>1){         list.add(res);         used[i]=true;         permute(ss, used, res+" "+ss[i], level+1, list)         used[i]=false;       }     } } function permuteword(s){   var ss;   for(var i=0; i<s.length;i++){       ss[i]=s[i];   }   var used;   for(var j=0; j<s.length;j++){       used[j]=false;   }   var result;   permute(ss, used, res, 0, result);   return result; } 

java , javascript may sound same aren't. take different appoaches doing different things. if in java checking console errors on running program, in javascript can check errors in browser console (open console f12)

populate array
javascript arrays don't have add() method. add value it, use push:
list.push(res)

populate array #2
in permuteword() function trying populate variable ss not initialized. compiler doesn't understand want put value. initialize ss empty array:
var ss = [];

typos
in first for loop have ss.lenght. fix that. check typos.

extra
in permuteword() passing res permute() function although don't have defined in function. things work if res global variable defined outside of functions.


and take advantage of browser console. every javascript developer (from noobie pro) has open!


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -