Coming back to this algorithm question I gave it another try to fix it and guess what, I DID IT! I took around 20 minutes to fix my code and pass through all the tests. First, I will explain what I did to my code compared to the yesterday's blog post.
function superIncreasing(arr) {
let temp = arr[0];
let result;
for (i = 1; i < arr.length; i++) {
for (j = 0; j < i; j++) {
if (arr[i] > temp) {
result = true
temp = temp + arr[j+1]
} else if (arr[i] <= temp) {
return false
}
}
}
return result;
};
I fixed 2 parts in my code. The first part is
} else if (arr[i] <= temp) {
return false
}
in this part I found out that if the previous number is larger than the current iterated index element which is a number type, I simply returned false right away because there is no need for the loop to go on if there is already a false statement(previous sum of elements in larger than the current number).
The second part was fixing the problem I found yesterday which is regarding the temporary value or initial value which I gave a name 'temp' to it. The code I wrote yesterday failed because there was a error in the part where everytime the loop starts again because the current number was larger than the second number, temp should become a sum of all the elements before the current iterated index value. Let's say in an array [2, 3, 7], temp is 2 because the code states that
let temp = arr[0];
Then because 2 is lesser than arr[1] which is 3, the loop goes again on to the top and comes down to compare arr[2] which is 7 now with the sums of the previous numbers which is arr[0] + arr[1] (2 + 3). This process was quite tricky but I fixed it by addding
for (j = 0; j < i; j++) {
if (arr[i] > temp) {
result = true
temp = temp + arr[j+1]
}
this part to the code. This part is initiated everytime the previous number is smaller than the current number that is iterated. Temp then also becomes temp + arr[j+1] which is a process to add the next element into the arr[0] which is 2 in the example I showed you. However, the reference code was a better way to solve this algorithm problem but I am still proud of me not giving up. However, I still will love to share the reference code here.
function superIncreasing(arr) {
let sum = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] <= sum) {
return false;
}
sum = sum + arr[i];
}
return true;
}
HAHA! much easier but I am still proud and will go to that level of mastering algorithm problems soon! Keep in touch!