I want some help to modify or create a function to do a simple task;
Here is my function:
function arra(sum, length){
var array = [];
for(let i = 0; i < length; i++) {
array.push(0);
}
//console.log(array)
for(let i = 0; i < sum; i++){
array[i] ++
}
return array;
}
console.log(arra(0, 7));
console.log(arra(3, 7));
console.log(arra(7, 7));
console.log(arra(10, 7));
Here first, we create an array with a length, then we push 0 to each element of it. so the array will be : [0, 0, 0, 0 ,0 ,0 ,0]
Then based on the value of sum I want to add 1 from the last element of the array to the beginning. The problem is I want to come back to the first element and keep adding 1 again if there is enough sum.
So if I execute this: arra(3, 7); I would have : [0, 0, 0, 0 ,1 ,1, 1]
if I execute this: arra(7, 7) I would have: [1, 1, 1, 1 ,1 ,1 ,1]
But the problem is when I execute this: arra(10, 7) I get : [1, 1, 1, 1, 1, 1, 1, NaN, NaN, NaN] that is unexpected . I want to have : [1, 1, 1, 1 ,2 ,2 ,2]
Another problem is I can't add to array from the last element to the first...
Edit: How can fix it guys?
for(let i = 0; i < sum; i++){ array[i] ++ }. You're indexing your array up to the value ofsum-1instead of maximum oflength-1. If you want to add to the array from the last element to the first, you can reverse your loop,for (i = last; i>= 0; i--) ...[0, 0, 0, 0 ,1 ,1, 1]your code says:[1, 1, 1, 0, 0, 0, 0]