Solving Puzzle Involving Mathematical Operations in the Arrays in Java

Breaking Into Sequential Pairs, Multiplication and Addition or Subtraction in Turn

Nickson Joram
Javarevisited
3 min readApr 29, 2021

--

In this article, we are going to see a simple Mathematical Operation based task that can be done in Arrays.

Recommended: Read about the Arrays in Java and Data Structures before continuing if needed.

Problem: (a[0] * a[1]) -(a[2] * a[3]) +(a[4] * a[5]) …

If there is an odd number of elements, then put the odd remaining number in a pair with 1 as the missing number e.g. -(a[6] * 1). Look at the following picture for more understanding.

Image by Author

So how to implement this? Our main method will look like this. The array of elements and a print statement calls another method passing the same array.

Let’s define the method addSubtractPairwise.

Let's let the machine know whether the array contains an odd number of elements or even.

We then, have to know how many pairs can be made from the array. It is obviously the length/2. And also we have to initialize the final output variable with the value 0. Also, a new array is created with the length of pairs to store the multiplied values.

Filling the newly created array can be done like this.

The addition or subtraction can be done in the following way.

When we get even positions, we have to add the values and have to subtract when we get odd positions. We have work left. If our array has an odd number of elements we have to consider the last element.

This is why we initiated and set a boolean value at the beginning. Let’s compile and execute it. What will be the output?

Let's add 13 as the last element of the array and execute the same program.

What will be the output?

Why?

We can try for various patterns like these and we can also implement this program in many alternate ways.

Try to implement some other better and alternate ways to solve this problem and share with me.

Hope the article can help. Share your thoughts too.

--

--