//2012-05-21 johnpfeiffer
// An equilibrium point in an array of integers is an Index where the sum of the left values equals the sum of the right values
// If there are no values to the left or right the sum is arbitrarily set to 0
// an O(n) solution maintains the running lefthand and righthand sums
public class Solution
{
public static void main(String[] args)
{
int a[] = { 1 , 2 , 0 , 3 };
int b[] = { -7 , 1 , 5 , 2 , -4 , 3, 0 };
displayArrayValues( a );
System.out.println( sum(a) + " = total Sum with no index selected" );
equi( a );
displayArrayValues( b );
System.out.println( sum(b) + " = total Sum with no index selected" );
equi( b );
}
private static void equi( int[] arrayOfIntegers )
{
if( arrayOfIntegers == null ){ throw new IllegalArgumentException(); }
int leftSum = 0;
int rightSum = sum( arrayOfIntegers );
int previousIndex = -1;
for( int currentIndex = 0; currentIndex < arrayOfIntegers.length; currentIndex++ , previousIndex++ )
{
if( previousIndex != -1 )
{ leftSum = leftSum + arrayOfIntegers[previousIndex];
}else
{ leftSum = 0;
}
rightSum = rightSum - arrayOfIntegers[currentIndex];
System.out.print( currentIndex + " : " + leftSum + " vs " + rightSum );
if( rightSum == leftSum )
{ System.out.print( " EQUILIBRIUM POINT!" );
}
System.out.println();
}
}
private static int sum( int[] arrayOfIntegers ) throws IllegalArgumentException
{
if( arrayOfIntegers == null ){ throw new IllegalArgumentException(); }
int sumOfIntegers = 0;
for( int i = 0; i < arrayOfIntegers.length; i++ )
{ sumOfIntegers += arrayOfIntegers[i];
}
return sumOfIntegers;
}
private static void displayArrayValues( int [] arrayOfIntegers )
{
if( arrayOfIntegers == null ){ throw new IllegalArgumentException(); }
for( int i = 0; i < arrayOfIntegers.length; i++ )
{ System.out.print( arrayOfIntegers[i] + " , " );
}
System.out.println();
}
} //end class