Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 29 additions & 45 deletions app/src/main/java/control/Double.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package control;

import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.stream.IntStream;

public class Double {
/**
* Sums all values squared from 0 to n
Expand All @@ -8,15 +13,8 @@ public class Double {
* @return The sum of the first n natural numbers squared.
*/
public static int sumSquare(int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
sum = sum + i * j;
}
}
}
return sum;
// Using the mathematical formula n(n+1)(2n+1)/6 for sum of squares
return n * (n + 1) * (2 * n + 1) / 6;
}

/**
Expand All @@ -26,13 +24,8 @@ public static int sumSquare(int n) {
* @return The sum of the first n triangular numbers.
*/
public static int sumTriangle(int n) {
int sum = 0;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < i; j++) {
sum = sum + j;
}
}
return sum;
// Using the mathematical formula n(n+1)(n+2)/6 for sum of triangular numbers
return n * (n + 1) * (n + 2) / 6;
}

/**
Expand All @@ -44,19 +37,15 @@ public static int sumTriangle(int n) {
* @return The number of pairs in the array.
*/
public static int countPairs(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
int nDuplicates = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
nDuplicates++;
}
}
if (nDuplicates == 2) {
count++;
}
}
return count / 2;
return (int) Arrays.stream(arr)
.boxed()
.collect(java.util.stream.Collectors.groupingBy(
i -> i,
java.util.stream.Collectors.counting()))
.values()
.stream()
.filter(count -> count == 2)
.count();
}

/**
Expand All @@ -68,15 +57,12 @@ public static int countPairs(int[] arr) {
* equal.
*/
public static int countDuplicates(int[] arr0, int[] arr1) {
int count = 0;
for (int i = 0; i < arr0.length; i++) {
for (int j = 0; j < arr1.length; j++) {
if (i == j && arr0[i] == arr1[j]) {
count++;
}
}
if (arr0 == null || arr1 == null) {
return 0;
}
return count;
return (int) IntStream.range(0, Math.min(arr0.length, arr1.length))
.filter(i -> arr0[i] == arr1[i])
.count();
}

/**
Expand All @@ -88,13 +74,11 @@ public static int countDuplicates(int[] arr0, int[] arr1) {
* @return The sum of all values in the 2D array.
*/
public static int sumMatrix(int[][] arr) {
int sum = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum += arr[i][j];
}
if (arr == null || arr.length == 0) {
return 0;
}
return sum;
return Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.sum();
}
}
}