Nguyen Chi Hieu Nguyen Chi Hieu - 4 months ago 9
Java Question

Convert permute method from Java to JavaScript

I implemented a Java code for permutation combination a string with input

str= "word1 word2 word3"
then 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 is 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;
}

for (int i = 0; i < ss.length; i++) {
// Check if the string is currently used
if (used[i]) {
continue;
}
// Check if res is empty or a 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 to JS code, I don't know what are errors in this 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;
}

Answer

Java and Javascript may sound almost the same but they aren't. They take different appoaches doing different things. If in Java You are checking the console for errors on running the program, then in Javascript you can check for the errors in the browser console (open console with F12)

POPULATE ARRAY
Javascript arrays don't have add() method. To add a value to it, use push:
list.push(res)

POPULATE ARRAY #2
In permuteword() function you are trying to populate variable ss that is not initialized. Compiler doesn't understand where you want to put that value. Initialize ss as an empty array:
var ss = [];

TYPOs
In the first for loop you have ss.lenght. Fix that. Always check for the typos.

EXTRA
In permuteword() you are passing res to the permute() function although you don't have it defined in the function. Things will work if res is a global variable defined outside of the functions.


And take advantage of that browser console. Every Javascript developer (from noobie to pro) has it always open!

Comments