Parsa_Gholipour :
Since the same code is working well in Java, there shouldn't be a logical problem. They are exactly same.
Java code:
public class ZeroOneGen {
public static void ZeroOneGen(int[] dataArr, int digits, int index) {
if (index == digits) {
String str = "";
for (int i = 0; i < digits; i++) {
str = str + dataArr[i];
}
System.out.println(str);
return;
}
for (int i = 0; i < 2; i++) {
dataArr[index] = i;
ZeroOneGen(dataArr, digits, index + 1);
}
}
public static void main(String[] args) {
int[] dataArrTemp = new int[3];
ZeroOneGen(dataArrTemp, 3, 0);
}
}
Output: 000 001 010 011 100 101 110 111
JS code:
function ZeroOneGen(dataArr, digits, index) {
if (index == digits) {
var str = "";
for (i = 0; i < digits; i++) {
str = str + dataArr[i];
}
console.log(str);
return;
}
for (z = 0; z < 2; z++) {
dataArr[index] = z;
ZeroOneGen(dataArr, digits, index + 1);
}
} // end function
var dataArrTemp = new Array(3);
ZeroOneGen(dataArrTemp, 3, 0);
output: 000 001
I expect it to continue and print other combinations as well. It stops at 001.
Nina Scholz :
You need to declare i
and z
because if not, you get global variables and this destroys iterating with recursive functions.
To prevent this and for getting an error, you could add 'strict mode';
at the beginning of the code.
Please have a look to the link, because it changes some other parts as well.
function ZeroOneGen(dataArr, digits, index) {
var i, z;
if (index == digits) {
var str = "";
for (i = 0; i < digits; i++) {
str = str + dataArr[i];
}
console.log(str)
return;
}
for (z = 0; z < 2; z++) {
dataArr[index] = z;
ZeroOneGen(dataArr, digits, index + 1);
}
}
var dataArrTemp = new Array(3);
ZeroOneGen(dataArrTemp, 3, 0);