I would like to write a program in Java which, given an array, finds the sum of all the numbers in the array - with an exception! Since the number 13 is very unlucky, I propose that we shall completely exclude the number 13, and the number directly after 13, if it exists, from the total sum.
The program, which I shall call sum13
, should produce the following results from the following inputs (these are just a few examples):
sum13([1,2,2,1]) = 6
This one is normal; no 13's here.
sum13([5, 13, 2]) = 5
The 13 and the number directly after the 13 are excluded.
sum13([13, 13]) = 0
The array contains only 13's, so neither of them are included.
sum13([1, 2, 13, 2, 1, 13]) = 4
A slightly longer example of the expected output.
Here is the code which I came up with for sum13
:
public int sum13(int[] nums) {
int sum = 0;
for (int i = 0; i < nums.length; i++) {
// we start by adding all the non-13s to the sum
if (nums[i] != 13) sum += nums[i];
}
// now we go back and remove all the non-13s directly after a 13
for (int j = 0; j < nums.length; j++) {
// the outermost loop checks if the numbers are a 13
if (nums[j] == 13 && j < nums.length - 1) {
for (int k = j + 1; k < nums.length; k++) {
// this loop checks that the number after the 13 is not a 13
if (nums[k] != 13) {
sum -= nums[k];
break;
}
}
}
}
return sum;
}
The program above works, although it does look quite messy!
Is there a better way of writing such a program that doesn't include multiple loops and nested if
s?