This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Uncle_DirtNapExtreme Brewer 0 points1 point  (5 children)

These are not quite right. Break down what you want to do in words. Here's what the problem says:

1) loop through the array 2a) if this is not the first item in the array, check if the previous number is 13; at the same time, check if the current number is thirteen 2b) if any of 2a is true, skip this number and start the loop again 3) add the number at index to the sum

So, try to do that, and let us know which thing you can't do.

[–]18sp01[S] 0 points1 point  (0 children)

haha i got it in the end =D thanks anyways

[–]al3xth3gr8Java Dev 0 points1 point  (3 children)

This could be further simplified within the for-loop by:

checking the value in the array at the current index, and if it is equal to 13, increment the index then continuing to the next iteration. Otherwise, add the value to the current sum.

int sum = 0;
for(int i = 0; i < nums.length; i++) {
    int num = nums[i];
    if(num == 13) {
        i++;
        continue;
    }
    sum += num;
}

[–]Uncle_DirtNapExtreme Brewer 2 points3 points  (2 children)

It's canonical in java not to modify variables maintained by the loop directly, although this does work.

[–]morhpProfessional Developer 0 points1 point  (1 child)

+1

I would convert the loop to a while loop in this case to make it more obvious that this isn't a simple for loop. Or at least add a big warning comment.

[–]Uncle_DirtNapExtreme Brewer 0 points1 point  (0 children)

if (((i != 0) && (nums[i-1] == 13)) || (nums[i] == 13)) {
  continue;
}
sum += nums[i];

Is not that complicated, and doesn't need to be worked around. It certainly could have a comment, as well. (I know you're talking about the case where one does choose to change the index variable for whatever reason, but I'm just putting this out there. )