I'm Developing a Code for java to Fold the element inside an array with example
A[0] = 2, A[1] = 7, A[2] = 9, A[3] = 7
Then Fold it with this format
A[0] = (A[0] + A[3]) mod 10 = 9
A[1] = (A[1] + A[2]) mod 10 = 6
And Fold it again until single
A[0] = (A[0] + A[1]) mod 10 = 5
Below are incomplete code:
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class ArrayFolder {
public static void main(String[] args) {
//ArrayList
int[] A = {
2,
7,
9,
7
};
//To define a new Array later
List<Integer> intList = new ArrayList<Integer>();
//To print the ArrayList A
for (int x = 0; x < A.length; x++) {
System.out.println("A[" + x + "]= " + A[x]);
}
//Function to fold the ArrayList into half
int res = 0;
int result = 0;
//if A.length is Even
if (A.length % 2 == 0) {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
}
//if A.length is Odd
else {
for (int i = 0; i < A.length / 2; i++) {
res = A[i] + A[A.length - 1 - i];
result = res % 10;
intList.add(result);
}
result = A[A.length / 2];
intList.add(result);
}
//add the int to New ArrayList
Integer[] intArray = new Integer[intList.size()];
intArray = intList.toArray(intArray);
System.out.println("\nNew Array ");
for (Integer s: intArray) {
System.out.println(s);
}
}
}
Compiled result
A[0]= 2
A[1]= 7
A[2]= 9
A[3]= 7
New Array
9
6
I couldn't find an efficient way to keep looping the function, so the code will stop folding when a single Integer achieved.
My question is, is there any efficient way to loop the process so later It can work with a larger element of Array?.
Kindly provide the logic or the code so I can continue with my code.
Many Thanks