Here we will find out minimum moves to equalize array elements. We will check the equality of elements from two arrays. As a pre-condition both arrays must have equal number of elements, i.e., in other words both arrays must be of same length.

We will read each element from both arrays one by one at a time and check how much difference are there between two elements at the same index of the arrays and add to the counter variable to keep track of the minimum movement.

**Prerequisite**

Knowledge of Java

Let’s move on to the example implementation…

The following Java source code will count minimum moves to equalize array elements.

Let’s say we have two arrays with elements as [123, 543] and [321, 279] respectively. Now to make each element equal at each index of the both arrays we have to add some value to the first array or to the second array.

To make equal at the first index of both arrays, 123 ~ 321. Now the first digit at 0-th index of first array is 1 and first digit at 0-th index of second array is 3. So here we need two moves 1->1+2=3.

Similarly, the second digits at the 0-th index of both arrays are equal. Therefore we don’t need any movement.

Now for third digit at 0-th index of first array is 3 and third digit at 0-th index of second array is 1. So we need to add value to the third digit at 0-th index of second array to make both values equal. So here again 1->1+2=3, need two movements.

Let’s check the following code to see it in action…

public class ArrayElementsEqualityCheck { public static void main(String[] args) { int[] a = new int[] { 123, 543 }; int[] b = new int[] { 321, 279 }; int countMove = countMoveToEqualArrayElements(a, b); System.out.println("Total moves to equal arrays: " + countMove); } private static int countMoveToEqualArrayElements(int[] a, int[] b) { int aLength = a.length; int counter = 0; if (a.length != b.length) { throw new RuntimeException("Make sure both arrays have equal elements"); } for (int i = 0; i < aLength; i++) { String as = String.valueOf(a[i]); String bs = String.valueOf(b[i]); for (int c = 0; c < as.length(); c++) { int aValue = Integer.parseInt(Character.toString(as.charAt(c))); int bValue = Integer.parseInt(Character.toString(bs.charAt(c))); if (aValue > bValue) { counter += aValue - bValue; } else { counter += bValue - aValue; } } } return counter; } }

**Testing the application**

When you run the above Java code then you will see the following output

`Total moves to equal arrays: 16`

Thanks for reading.