Finding the sum of numbers in an array - excluding the number 13 and the number directly after it

AnagramDatagram :

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 ifs?

Kepotx :

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;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Squaring numbers in array, finding the sum and the biggest number

Return the sum of the numbers in the array, except number 13

Finding a number that is sum of two other numbers in a sorted array

Sum of integers, not counting 13 and the number after 13

Finding closest sum of numbers to a given number

Regex: Finding number by capturing but excluding

Finding the sum of a given number

finding the sum of numbers in an array

In Javascript generate a random whole number excluding array of numbers

Finding 2 pentagonal numbers whose sum and difference produce pentagonal number

Finding nearest next number for n, with sum of multiple of 2 numbers

Finding three numbers whose sum is divisible by a given number

Finding if a number is a perfect square through sum of odd numbers

Sum the factors of a number (excluding the number itself)

Bigger number in array than the sum of the numbers to the right of it

Create an Array with the numbers needed to sum a specific number

Finding the number of elements in an array to be replaced by a given number such that the sum of the array is smaller than another given number

Finding the minimum number which when added to running sum of array is 1

Finding three elements in an array whose sum is closest to a given number

Sum the odds numbers of a "number"

finding the nearest number in an array

Finding sum of number nearest to specific number

finding sum of numbers in a char array

Finding number of positive numbers in list

Generate random number in range excluding some numbers

generating random number excluding some numbers

Sum of random list numbers after 1st negative number

Is there any way to reduce number of operations for finding and returning the number of triplets sum in array which is equals to any integer X

Using binary search for finding the number that appears odd number of times in an array of numbers

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive