# Untitled

unknown
java
6 months ago
2.1 kB
3
Indexable
Never
```import java.util.Arrays;

public class WeightPoint {

// Mamy na wejściu tablicę liczb i musimy zwrócić indeks elementu, który jest środkiem ciężkości
// (suma elementów z lewej równa jest sumie elementów z prawej)

public static void main(String[] args) {
int[] arr1 = new int[]{1, 2, 3, 3, 2, 1};
int[] arr2 = new int[]{1, 2, 100, 3, 2, 1};
int[] arr3 = new int[]{1, 6, 1, 2, 4};
int[] arr4 = new int[]{1, 1};
int[] arr5 = new int[]{20};

System.out.println("weightPoint");
System.out.println("Arr1: " + weightPoint(arr1));
System.out.println("Arr2: " + weightPoint(arr2));
System.out.println("Arr3: " + weightPoint(arr3));
System.out.println("Arr4: " + weightPoint(arr4));
System.out.println("Arr5: " + weightPoint(arr5));

System.out.println("weightPointV2");
System.out.println("Arr1: " + weightPointV2(arr1));
System.out.println("Arr2: " + weightPointV2(arr2));
System.out.println("Arr3: " + weightPointV2(arr3));
System.out.println("Arr4: " + weightPointV2(arr4));
System.out.println("Arr5: " + weightPointV2(arr5));
}

private static int weightPoint(int[] array) {
for (int i = 1; i < array.length; i++) {
int sumLeft = 0;
for (int j = 0; j < i; j++) {
sumLeft += array[j];
}

int sumRight = 0;
for (int j = i; j < array.length; j++) {
sumRight += array[j];
}

if (sumLeft == sumRight) {
return i;
}
}

return -1;
}

private static int weightPointV2(int[] array) {
int sumLeft = 0;
int sumRight = Arrays.stream(array).sum();
for (int i = 0; i < array.length; i++) {
sumLeft += array[i];
sumRight -= array[i];

if (sumLeft == sumRight) {
return i + 1;
}
}

return -1;
}
}
```