From 162bd10d6d4a280b3db4d7bf2999bda56a5c7cb3 Mon Sep 17 00:00:00 2001 From: TurinTech Bot Date: Wed, 22 Jan 2025 12:25:49 +0000 Subject: [PATCH] Artemis Changes --- app/src/main/java/control/Double.java | 56 +++++++++++---------------- 1 file changed, 23 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/control/Double.java b/app/src/main/java/control/Double.java index cc5cf15..53aae3d 100644 --- a/app/src/main/java/control/Double.java +++ b/app/src/main/java/control/Double.java @@ -1,5 +1,8 @@ package control; +import java.util.HashMap; +import java.util.Map; + public class Double { /** * Sums all values squared from 0 to n @@ -8,15 +11,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; + // Use the direct formula for sum of squares: n(n+1)(2n+1)/6 + return n * (n + 1) * (2 * n + 1) / 6; } /** @@ -26,13 +22,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; + // Use the direct formula for sum of triangular numbers: n(n+1)(n+2)/6 + return n * (n + 1) * (n + 2) / 6; } /** @@ -44,21 +35,21 @@ 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++; + Map counts = new HashMap<>(); + for (int num : arr) { + counts.put(num, counts.getOrDefault(num, 0) + 1); + } + + int pairs = 0; + for (int count : counts.values()) { + if (count == 2) { + pairs++; } } - return count / 2; + return pairs / 2; //Divide pairs by two since each pair was counted twice } + /** * Counts the number of instances where the values at the same index are equal * @@ -69,11 +60,10 @@ public static int countPairs(int[] arr) { */ 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++; - } + int minLength = Math.min(arr0.length, arr1.length); // Get min length to avoid index out of bound + for (int i = 0; i < minLength; i++) { + if (arr0[i] == arr1[i]) { + count++; } } return count; @@ -97,4 +87,4 @@ public static int sumMatrix(int[][] arr) { } return sum; } -} +} \ No newline at end of file