Minimum Moves to Equalize Array Elements

Introduction

Here I will show you how to find out minimum moves to equalize array elements. I 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.

I 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 both arrays and add to the counter variable to keep track of the minimum movement.

Prerequisite

Knowledge of Java

Equalize Array Elements

Let’s move on to the example implementation…

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

Let’s say you 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 you 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 you need two moves 1->1+2=3.

Similarly, the second digits at the 0-th index of both arrays are equal. Therefore you 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 you 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.

Java Class

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

package com.roytuts.java.minimum.moves.equalize.array.elements;

public class EqualizeArrayElementsApp {

	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 Program

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

Total moves to equal arrays: 16

That’s all about equalizing array elements using Java program.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *