Last active
August 29, 2015 13:55
Tape Equilibrium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment