Question :
I am testing a code snippet here in javascript and it is giving syntax error on line 12. It says that there is a ;
missing somewhere, but I have already rolled that code and can not find the error.
This code was originally written in C and I’m trying to adapt to a specific problem using javascript. I have changed values set to integers for var
, I have already changed to type char
since javascript is weakly typed and ==
means that it “skips” the type differences of the variables.
var arr = ["1", "2", "3", "4", "5"];
var r = "3";
var n = (arr.length)/(arr[0].length);
var data[r];
function combinationUtil(var arr[], var data[], var start, var end, var index, var r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
for (var j=0; j<r; j++){
console.log(data[j]);
//document.getElementById("demo").innerHTML = data[j];
}
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (var i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
combinationUtil(arr, data, 0, n-1, 0, r);
<p id="demo"></p>
Answer :
In addition to the syntax error pointed out by @YurePereira, we still have the error of line 12:
var data[r];
You are declaring this array the wrong way, in which case you have two options:
Without informing the size of the array, let the JavaScript set it at runtime.
var data = [];
Create an Array object of size r.
var data = new Array(r);
Here’s how your script works:
var data = [];
var arr = [1, 2, 3, 4, 5];
var r = 3;
var n = arr.length;
var demo = document.getElementById("demo");
function combinationUtil(arr, data, start, end, index, r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
var demo = document.createElement("div");
demo.innerHTML = JSON.stringify(data.slice(0, r));
document.body.appendChild(demo);
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (var i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
combinationUtil(arr, data, 0, n-1, 0, r);
Remove the var
and the [] of the parameters of the combinationUtil
function, because of the way it is, it gives a syntax error.
function combinationUtil(arr, data, start, end, index, r)
{
if (index == r)
{
for (var j = 0; j < r; j++) {
console.log(data[j]);
}
}
for (var i = start; i <= end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}