HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find the sum and multiply equilibrium

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findtheequilibriummultiplysumand

Problem

This finds the equilibrium. For sum/mult an equilibrium is defined as the index i at which sum/mult of all elements at index j respectively. Edge cases are documented clearly in JavaDocs.

Note: I do understand merits of unit testing in separate files. But deliberately added it to main method for personal convenience, so I request that you don't consider that in your feedback.

I'm looking for request code review, optimizations and best practices.

```
public final class EquilibriumIndex {

private EquilibriumIndex() {}

/**
* Returns index, if equilibrium is found, else returns 0.
* If multiple equilibrium exists then, the first equilibrium is returned.
* Note: end of array is also treated as an equilibrium.
*
* Eg - 1:
* [-7, 8, -2, 8, -7, 0]
* has 2 equilibrium
* a[2] = -2;
* a[5] = 0;
* in such case position 2 is returned
*
* Eg -2:
* [0, -7, 8, -2, 8, -7]
* has 2 equilibrium
* a[0] = 0;
* a[3] = -2;
* in such case position 0 is returned
*
* @param a the int array
* @returns the index if found, else returns -1.
*/
public static int getSumEquilibrium(int[] a) {
int sum = 0; // the sum of all contents
int leftSum = 0; // the sum which starts from the left side.

for (int i : a) {
sum += i;
}
for (int i = 0; i < a.length; i++) {
sum -= a[i];
if (sum == leftSum) {
return i;
}
leftSum += a[i];
}

return -1;
}

private static int processZero (int[] a, int i) {
// if index i is the first element of the array.
if (i == 0) {
for (int j = i + 1; j < a.length; j++) {
// eg: [0, 1, 2, 0, 5], equilibrium is the first element.
if (a[j] == 0) {
return 0;
}
}
//eg: [0, 1, 2,

Solution

getMultEquilibrium() is supposed to return an array index (or -1 if there is no such index). It makes no sense that the array index be a double, as array indexes must be ints. Therefore,

public static double getMultEquilibrium(int[] a)


should be

public static int getMultEquilibrium(int[] a)

Code Snippets

public static double getMultEquilibrium(int[] a)
public static int getMultEquilibrium(int[] a)

Context

StackExchange Code Review Q#47114, answer score: 5

Revisions (0)

No revisions yet.