Solving Puzzle Involving Mathematical Operations in the Arrays in Java
Breaking Into Sequential Pairs, Multiplication and Addition or Subtraction in Turn
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.
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.
public static void main(String [] args) {
int [] array = {5, 4, 1, 9, 6, 7};
System.out.println(addSubtractPairwise(array));
}
Let’s define the method addSubtractPairwise.
public static int addSubtractPairwise (int[] arg) { //code }
Let's let the machine know whether the array contains an odd number of elements or even.
boolean even = false;
if(arg.length % 2 == 0) {
even = true;
}
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.
int numberOfPairs = arg.length/2;
int sum = 0;
int [] mul = new int [numberOfPairs];
Filling the newly created array can be done like this.
for (int j = 0; j < numberOfPairs; j ++) {
mul[j] = arg[j*2]*arg[(j*2)+1];
}
The addition or subtraction can be done in the following way.
for (int j = 0; j < numberOfPairs; j ++) {
if(j%2 ==0){
sum = sum + mul[j];
} else {
sum = sum - mul[j];
}
}
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.
if(even) {
return sum;
} else {
if(numberOfPairs%2 ==0){
sum = sum + arg[arg.length-1];
} else {
sum = sum - arg[arg.length-1];
}
return sum;
}
This is why we initiated and set a boolean value at the beginning. Let’s compile and execute it. What will be the output?
53
Let's add 13 as the last element of the array and execute the same program.
int [] array = {5, 4, 1, 9, 6, 7, 13};
System.out.println(addSubtractPairwise(array));
What will be the output?
40
Why?
53 - (13 x 1) = 40
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.