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?
You can find the sum of all elements in an array by following the approach below: Initialize a variable sum to store the total sum of all elements of the array. Traverse the array and add each element of the array with the sum variable. Finally, return the sum variable.
Python provides an inbuilt function sum() which sums up the numbers in the list.
Find the sum of the numbers in the range [1, N] using the formula N * (N+1)/2. Now find the sum of all the elements in the array and subtract it from the sum of the first N natural numbers. This will give the value of the missing element.
Well, you use i as iterator. just make i++
when the current number is 13. This way, not only you don't add 13 to the sum but you also skip the next value.
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];
}
else {
i++;
}
}
return sum;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With