If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Wednesday, January 29, 2014

Code puzzler: Tape Equilibrium

Suppose you get an array of ints of arbitrary length. Now we need to find out what is the mimimal absolute difference of the 2 sums of numbers if you split the array at any position in a left and right array. And preferably in a efficient way.
import java.util.ArrayList;
import java.util.List;
public class TapeEquilibrium {
public static void main(String[] args) {
int [] numbers1 = {1,3,2,7};
int [] numbers2 = {5,2,8,4};
evaluate(numbers1, 1);
evaluate(numbers2, 5);
}
public static void evaluate(int [] numbers, int expected) {
int answer = solution(numbers);
System.out.println("Expected answer = " + expected + ", got " + answer);
}
public static int solution(int[] A) {
List<Integer> numbers = toList(A);
int size = numbers.size();
int sumLeft = numbers.get(0);
int sumRight = sum(numbers.subList(1, size));
int minDifference = Math.abs(sumLeft - sumRight);
for (int i : numbers.subList(1, size -1)) {
sumLeft = sumLeft + i;
sumRight = sumRight - i;
int difference = Math.abs(sumLeft - sumRight);
if (difference < minDifference) {
minDifference = difference;
}
}
return minDifference;
}
public static List<Integer> toList(int [] array) {
List<Integer> result = new ArrayList<Integer>();
for (int ele : array) {
result.add(new Integer(ele));
}
return result;
}
public static int sum(List<Integer> numbers) {
int sumRight = 0;
for (int i : numbers) {
sumRight += i;
}
return sumRight;
}
}
view raw gistfile1.java hosted with ❤ by GitHub

4 comments:

  1. It has reminded me of the in-place version of quicksort algorithm: http://en.wikipedia.org/wiki/Quicksort#In-place_version

    BTW, a couple of improvements to your implementation:
    1. You should avoid using Arrays.copyOfRange. It's so inefficient.
    2. You can immediately break the loop as soon as the following becomes true: (difference > minDifference).

    ReplyDelete
  2. Well, my second point is incorrect if there may be negative ints.

    ReplyDelete
  3. Yeah.... arrays are a pain to work with... I probably should convert the int array to a List first but even that takes a few lines of code extra... java does not autobox them unfortunately. But with a list I can easily take subLists.

    ReplyDelete
  4. Hi, Thanks for this great image that explores and helps me to understand what the Tape-Equilibrium is!.

    ReplyDelete