I trying to push an array I've generated to a multidimensional array, and for some reason the value of all the other positions in the array's values, are the same as the value I just pushed.
For example: I do
var grades = [];
for(var i = 0; i < num_qes + 1; i++){
var grade = [0, 0, 0, 0];
grade[0] = i;
for(var n = 0; n < num_qes+ 1; n++){
grade[1] = n;
for(var f = 0; f < num_qes+ 1; f++){
grade[2] = f;
for(var t = 0; t < num_qes+ 1; t++){
grade[3] = t;
allGrad = grade[0] + grade[1] + grade[2] + grade[3];
//println(allGrad);
if(allGrad === num_qes){
grades.push(grade);
}
}
}
}
Here at the end I check to see if all of the values in my generated array are exactly equal to the number of questions.
if(allGrad === num_qes){
grades.push(grade);
}
Let's say that grade = [9, 1, 0, 0], when I push this value to the multidimensional array, grades, all the values change to [9, 1, 0, 0]. So the multidimensional array looks like this: [[9, 1, 0, 0], [9, 1, 0, 0], [9, 1, 0, 0]], when it SHOULD look like this: [[9, 0, 0, 1], [9, 0, 1, 0], [9, 1, 0, 0]].
I hope what I said make senses, and thanks in advance for ansnewing.
The jsfiddle is right here
-
1Could you add a jsfiddle with a not-working example for better understanding please.Kiril– Kiril2016年01月11日 20:53:55 +00:00Commented Jan 11, 2016 at 20:53
-
1Are you trying to get all combinations where the sum of the 4 values equals num_qes?Quantumplate– Quantumplate2016年01月11日 20:58:30 +00:00Commented Jan 11, 2016 at 20:58
-
Yes, I only need all the combinations where the sum is 4.TheRailsRouter– TheRailsRouter2016年01月11日 21:07:52 +00:00Commented Jan 11, 2016 at 21:07
-
The jsfiddle is right here, I'm trying to get the page to display the results.TheRailsRouter– TheRailsRouter2016年01月11日 21:10:39 +00:00Commented Jan 11, 2016 at 21:10
1 Answer 1
Is this what you are after?
var grades = [];
var num_qes = 4;
for(var i = 0; i <= num_qes; i++){
for(var n = 0; n <= num_qes; n++){
for(var f = 0; f <= num_qes; f++){
for(var t = 0; t <= num_qes; t++){
var sum = i + n + f + t;
if(sum === num_qes){
console.log(i + ',' + n + ',' + f + ',' + t);
var grade = [i, n, f, t];
grades.push(grade);
}
}
}
}
}
Notes:
- I've replaced
i < num_qes + 1withi <= num_quesfor simplicity - Only creating the grade array in the inner loop when your condition is met (makes it much more readable)
- Summing the numbers directly rather than reading from the grade array you've just populated (again more readable)
- Using console.log() to output results that match criteria
Results in console look like this...
0,0,0,4
0,0,1,3
0,0,2,2
0,0,3,1
0,0,4,0
0,1,0,3
0,1,1,2
0,1,2,1
0,1,3,0
etc
4 Comments
Explore related questions
See similar questions with these tags.