add Java code to optimize with tests

This commit is contained in:
HeshamHM28 2026-01-30 17:34:16 +02:00
parent 29f266ee63
commit cbb532fcfd
17 changed files with 2830 additions and 11 deletions

View file

@ -4,13 +4,12 @@ import java.util.ArrayList;
import java.util.List;
/**
* Collection of algorithms that can be optimized by Codeflash.
* Collection of algorithms.
*/
public class Algorithms {
/**
* Calculate Fibonacci number using naive recursive approach.
* This has O(2^n) time complexity and should be optimized.
* Calculate Fibonacci number using recursive approach.
*
* @param n The position in Fibonacci sequence (0-indexed)
* @return The nth Fibonacci number
@ -23,8 +22,7 @@ public class Algorithms {
}
/**
* Find all prime numbers up to n using naive approach.
* This can be optimized with Sieve of Eratosthenes.
* Find all prime numbers up to n.
*
* @param n Upper bound for finding primes
* @return List of all prime numbers <= n
@ -40,7 +38,7 @@ public class Algorithms {
}
/**
* Check if a number is prime using naive trial division.
* Check if a number is prime using trial division.
*
* @param num Number to check
* @return true if num is prime
@ -56,8 +54,7 @@ public class Algorithms {
}
/**
* Find duplicates in an array using O(n^2) nested loops.
* This can be optimized with HashSet to O(n).
* Find duplicates in an array using nested loops.
*
* @param arr Input array
* @return List of duplicate elements
@ -75,7 +72,7 @@ public class Algorithms {
}
/**
* Calculate factorial recursively without tail optimization.
* Calculate factorial recursively.
*
* @param n Number to calculate factorial for
* @return n!
@ -89,7 +86,6 @@ public class Algorithms {
/**
* Concatenate strings in a loop using String concatenation.
* Should be optimized to use StringBuilder.
*
* @param items List of strings to concatenate
* @return Concatenated result
@ -107,7 +103,6 @@ public class Algorithms {
/**
* Calculate sum of squares using a loop.
* This is already efficient but shows a simple example.
*
* @param n Upper bound
* @return Sum of squares from 1 to n

View file

@ -0,0 +1,331 @@
package com.example;
import java.util.ArrayList;
import java.util.List;
/**
* Array utility functions.
*/
public class ArrayUtils {
/**
* Find all duplicate elements in an array using nested loops.
*
* @param arr Input array
* @return List of duplicate elements
*/
public static List<Integer> findDuplicates(int[] arr) {
List<Integer> duplicates = new ArrayList<>();
if (arr == null || arr.length < 2) {
return duplicates;
}
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j] && !duplicates.contains(arr[i])) {
duplicates.add(arr[i]);
}
}
}
return duplicates;
}
/**
* Remove duplicates from array using nested loops.
*
* @param arr Input array
* @return Array without duplicates
*/
public static int[] removeDuplicates(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
List<Integer> unique = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
boolean found = false;
for (int j = 0; j < unique.size(); j++) {
if (unique.get(j) == arr[i]) {
found = true;
break;
}
}
if (!found) {
unique.add(arr[i]);
}
}
int[] result = new int[unique.size()];
for (int i = 0; i < unique.size(); i++) {
result[i] = unique.get(i);
}
return result;
}
/**
* Linear search through array.
*
* @param arr Array to search
* @param target Value to find
* @return Index of target, or -1 if not found
*/
public static int linearSearch(int[] arr, int target) {
if (arr == null) {
return -1;
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
/**
* Find intersection of two arrays using nested loops.
*
* @param arr1 First array
* @param arr2 Second array
* @return Array of common elements
*/
public static int[] findIntersection(int[] arr1, int[] arr2) {
if (arr1 == null || arr2 == null) {
return new int[0];
}
List<Integer> intersection = new ArrayList<>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j] && !intersection.contains(arr1[i])) {
intersection.add(arr1[i]);
}
}
}
int[] result = new int[intersection.size()];
for (int i = 0; i < intersection.size(); i++) {
result[i] = intersection.get(i);
}
return result;
}
/**
* Find union of two arrays using nested loops.
*
* @param arr1 First array
* @param arr2 Second array
* @return Array of all unique elements from both arrays
*/
public static int[] findUnion(int[] arr1, int[] arr2) {
List<Integer> union = new ArrayList<>();
if (arr1 != null) {
for (int i = 0; i < arr1.length; i++) {
if (!union.contains(arr1[i])) {
union.add(arr1[i]);
}
}
}
if (arr2 != null) {
for (int i = 0; i < arr2.length; i++) {
if (!union.contains(arr2[i])) {
union.add(arr2[i]);
}
}
}
int[] result = new int[union.size()];
for (int i = 0; i < union.size(); i++) {
result[i] = union.get(i);
}
return result;
}
/**
* Reverse an array.
*
* @param arr Array to reverse
* @return Reversed array
*/
public static int[] reverseArray(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[arr.length - 1 - i];
}
return result;
}
/**
* Rotate array to the right by k positions.
*
* @param arr Array to rotate
* @param k Number of positions to rotate
* @return Rotated array
*/
public static int[] rotateRight(int[] arr, int k) {
if (arr == null || arr.length == 0 || k == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
k = k % result.length;
for (int rotation = 0; rotation < k; rotation++) {
int last = result[result.length - 1];
for (int i = result.length - 1; i > 0; i--) {
result[i] = result[i - 1];
}
result[0] = last;
}
return result;
}
/**
* Count occurrences of each element using nested loops.
*
* @param arr Input array
* @return 2D array where [i][0] is element and [i][1] is count
*/
public static int[][] countOccurrences(int[] arr) {
if (arr == null || arr.length == 0) {
return new int[0][0];
}
List<int[]> counts = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
boolean found = false;
for (int j = 0; j < counts.size(); j++) {
if (counts.get(j)[0] == arr[i]) {
counts.get(j)[1]++;
found = true;
break;
}
}
if (!found) {
counts.add(new int[]{arr[i], 1});
}
}
int[][] result = new int[counts.size()][2];
for (int i = 0; i < counts.size(); i++) {
result[i] = counts.get(i);
}
return result;
}
/**
* Find the k-th smallest element using repeated minimum finding.
*
* @param arr Input array
* @param k Position (1-indexed)
* @return k-th smallest element
*/
public static int kthSmallest(int[] arr, int k) {
if (arr == null || arr.length == 0 || k <= 0 || k > arr.length) {
throw new IllegalArgumentException("Invalid input");
}
int[] copy = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
copy[i] = arr[i];
}
for (int i = 0; i < k; i++) {
int minIdx = i;
for (int j = i + 1; j < copy.length; j++) {
if (copy[j] < copy[minIdx]) {
minIdx = j;
}
}
int temp = copy[i];
copy[i] = copy[minIdx];
copy[minIdx] = temp;
}
return copy[k - 1];
}
/**
* Check if array contains a subarray using brute force.
*
* @param arr Main array
* @param subArr Subarray to find
* @return Starting index of subarray, or -1 if not found
*/
public static int findSubarray(int[] arr, int[] subArr) {
if (arr == null || subArr == null || subArr.length > arr.length) {
return -1;
}
if (subArr.length == 0) {
return 0;
}
for (int i = 0; i <= arr.length - subArr.length; i++) {
boolean match = true;
for (int j = 0; j < subArr.length; j++) {
if (arr[i + j] != subArr[j]) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
/**
* Merge two sorted arrays.
*
* @param arr1 First sorted array
* @param arr2 Second sorted array
* @return Merged sorted array
*/
public static int[] mergeSortedArrays(int[] arr1, int[] arr2) {
if (arr1 == null) arr1 = new int[0];
if (arr2 == null) arr2 = new int[0];
int[] result = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
result[k] = arr1[i];
i++;
} else {
result[k] = arr2[j];
j++;
}
k++;
}
while (i < arr1.length) {
result[k] = arr1[i];
i++;
k++;
}
while (j < arr2.length) {
result[k] = arr2[j];
j++;
k++;
}
return result;
}
}

View file

@ -0,0 +1,154 @@
package com.example;
/**
* Sorting algorithms.
*/
public class BubbleSort {
/**
* Sort an array using bubble sort algorithm.
*
* @param arr Array to sort
* @return New sorted array (ascending order)
*/
public static int[] bubbleSort(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
int n = result.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (result[j] > result[j + 1]) {
int temp = result[j];
result[j] = result[j + 1];
result[j + 1] = temp;
}
}
}
return result;
}
/**
* Sort an array in descending order using bubble sort.
*
* @param arr Array to sort
* @return New sorted array (descending order)
*/
public static int[] bubbleSortDescending(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
int n = result.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (result[j] < result[j + 1]) {
int temp = result[j];
result[j] = result[j + 1];
result[j + 1] = temp;
}
}
}
return result;
}
/**
* Sort an array using insertion sort algorithm.
*
* @param arr Array to sort
* @return New sorted array
*/
public static int[] insertionSort(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
int n = result.length;
for (int i = 1; i < n; i++) {
int key = result[i];
int j = i - 1;
while (j >= 0 && result[j] > key) {
result[j + 1] = result[j];
j = j - 1;
}
result[j + 1] = key;
}
return result;
}
/**
* Sort an array using selection sort algorithm.
*
* @param arr Array to sort
* @return New sorted array
*/
public static int[] selectionSort(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
int n = result.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (result[j] < result[minIdx]) {
minIdx = j;
}
}
int temp = result[minIdx];
result[minIdx] = result[i];
result[i] = temp;
}
return result;
}
/**
* Check if an array is sorted in ascending order.
*
* @param arr Array to check
* @return true if sorted in ascending order
*/
public static boolean isSorted(int[] arr) {
if (arr == null || arr.length <= 1) {
return true;
}
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
}

View file

@ -0,0 +1,190 @@
package com.example;
import java.util.HashMap;
import java.util.Map;
/**
* Calculator for statistics.
*/
public class Calculator {
/**
* Calculate statistics for an array of numbers.
*
* @param numbers Array of numbers to analyze
* @return Map containing sum, average, min, max, and range
*/
public static Map<String, Double> calculateStats(double[] numbers) {
Map<String, Double> stats = new HashMap<>();
if (numbers == null || numbers.length == 0) {
stats.put("sum", 0.0);
stats.put("average", 0.0);
stats.put("min", 0.0);
stats.put("max", 0.0);
stats.put("range", 0.0);
return stats;
}
double sum = MathHelpers.sumArray(numbers);
double avg = MathHelpers.average(numbers);
double min = MathHelpers.findMin(numbers);
double max = MathHelpers.findMax(numbers);
double range = max - min;
stats.put("sum", sum);
stats.put("average", avg);
stats.put("min", min);
stats.put("max", max);
stats.put("range", range);
return stats;
}
/**
* Normalize an array of numbers to a 0-1 range.
*
* @param numbers Array of numbers to normalize
* @return Normalized array
*/
public static double[] normalizeArray(double[] numbers) {
if (numbers == null || numbers.length == 0) {
return new double[0];
}
double min = MathHelpers.findMin(numbers);
double max = MathHelpers.findMax(numbers);
double range = max - min;
double[] result = new double[numbers.length];
if (range == 0) {
for (int i = 0; i < numbers.length; i++) {
result[i] = 0.5;
}
return result;
}
for (int i = 0; i < numbers.length; i++) {
result[i] = (numbers[i] - min) / range;
}
return result;
}
/**
* Calculate the weighted average of values with corresponding weights.
*
* @param values Array of values
* @param weights Array of weights (same length as values)
* @return The weighted average
*/
public static double weightedAverage(double[] values, double[] weights) {
if (values == null || weights == null) {
return 0;
}
if (values.length == 0 || values.length != weights.length) {
return 0;
}
double weightedSum = 0;
for (int i = 0; i < values.length; i++) {
weightedSum = weightedSum + values[i] * weights[i];
}
double totalWeight = MathHelpers.sumArray(weights);
if (totalWeight == 0) {
return 0;
}
return weightedSum / totalWeight;
}
/**
* Calculate the variance of an array.
*
* @param numbers Array of numbers
* @return Variance
*/
public static double variance(double[] numbers) {
if (numbers == null || numbers.length == 0) {
return 0;
}
double mean = MathHelpers.average(numbers);
double sumSquaredDiff = 0;
for (int i = 0; i < numbers.length; i++) {
double diff = numbers[i] - mean;
sumSquaredDiff = sumSquaredDiff + diff * diff;
}
return sumSquaredDiff / numbers.length;
}
/**
* Calculate the standard deviation of an array.
*
* @param numbers Array of numbers
* @return Standard deviation
*/
public static double standardDeviation(double[] numbers) {
return Math.sqrt(variance(numbers));
}
/**
* Calculate the median of an array.
*
* @param numbers Array of numbers
* @return Median value
*/
public static double median(double[] numbers) {
if (numbers == null || numbers.length == 0) {
return 0;
}
int[] intArray = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intArray[i] = (int) numbers[i];
}
int[] sorted = BubbleSort.bubbleSort(intArray);
int mid = sorted.length / 2;
if (sorted.length % 2 == 0) {
return (sorted[mid - 1] + sorted[mid]) / 2.0;
} else {
return sorted[mid];
}
}
/**
* Calculate percentile value.
*
* @param numbers Array of numbers
* @param percentile Percentile to calculate (0-100)
* @return Value at the specified percentile
*/
public static double percentile(double[] numbers, int percentile) {
if (numbers == null || numbers.length == 0) {
return 0;
}
if (percentile < 0 || percentile > 100) {
throw new IllegalArgumentException("Percentile must be between 0 and 100");
}
int[] intArray = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intArray[i] = (int) numbers[i];
}
int[] sorted = BubbleSort.bubbleSort(intArray);
int index = (int) Math.ceil((percentile / 100.0) * sorted.length) - 1;
index = Math.max(0, Math.min(index, sorted.length - 1));
return sorted[index];
}
}

View file

@ -0,0 +1,175 @@
package com.example;
import java.util.ArrayList;
import java.util.List;
/**
* Fibonacci implementations.
*/
public class Fibonacci {
/**
* Calculate the nth Fibonacci number using recursion.
*
* @param n Position in Fibonacci sequence (0-indexed)
* @return The nth Fibonacci number
*/
public static long fibonacci(int n) {
if (n < 0) {
throw new IllegalArgumentException("Fibonacci not defined for negative numbers");
}
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
/**
* Check if a number is a Fibonacci number.
*
* @param num Number to check
* @return true if num is a Fibonacci number
*/
public static boolean isFibonacci(long num) {
if (num < 0) {
return false;
}
long check1 = 5 * num * num + 4;
long check2 = 5 * num * num - 4;
return isPerfectSquare(check1) || isPerfectSquare(check2);
}
/**
* Check if a number is a perfect square.
*
* @param n Number to check
* @return true if n is a perfect square
*/
public static boolean isPerfectSquare(long n) {
if (n < 0) {
return false;
}
long sqrt = (long) Math.sqrt(n);
return sqrt * sqrt == n;
}
/**
* Generate an array of the first n Fibonacci numbers.
*
* @param n Number of Fibonacci numbers to generate
* @return Array of first n Fibonacci numbers
*/
public static long[] fibonacciSequence(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be non-negative");
}
if (n == 0) {
return new long[0];
}
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = fibonacci(i);
}
return result;
}
/**
* Find the index of a Fibonacci number.
*
* @param fibNum The Fibonacci number to find
* @return Index of the number, or -1 if not a Fibonacci number
*/
public static int fibonacciIndex(long fibNum) {
if (fibNum < 0) {
return -1;
}
if (fibNum == 0) {
return 0;
}
if (fibNum == 1) {
return 1;
}
int index = 2;
while (true) {
long fib = fibonacci(index);
if (fib == fibNum) {
return index;
}
if (fib > fibNum) {
return -1;
}
index++;
if (index > 50) {
return -1;
}
}
}
/**
* Calculate sum of first n Fibonacci numbers.
*
* @param n Number of Fibonacci numbers to sum
* @return Sum of first n Fibonacci numbers
*/
public static long sumFibonacci(int n) {
if (n <= 0) {
return 0;
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + fibonacci(i);
}
return sum;
}
/**
* Get all Fibonacci numbers less than a given limit.
*
* @param limit Upper bound (exclusive)
* @return List of Fibonacci numbers less than limit
*/
public static List<Long> fibonacciUpTo(long limit) {
List<Long> result = new ArrayList<>();
if (limit <= 0) {
return result;
}
int index = 0;
while (true) {
long fib = fibonacci(index);
if (fib >= limit) {
break;
}
result.add(fib);
index++;
if (index > 50) {
break;
}
}
return result;
}
/**
* Check if two numbers are consecutive Fibonacci numbers.
*
* @param a First number
* @param b Second number
* @return true if a and b are consecutive Fibonacci numbers
*/
public static boolean areConsecutiveFibonacci(long a, long b) {
if (!isFibonacci(a) || !isFibonacci(b)) {
return false;
}
int indexA = fibonacciIndex(a);
int indexB = fibonacciIndex(b);
return Math.abs(indexA - indexB) == 1;
}
}

View file

@ -0,0 +1,325 @@
package com.example;
import java.util.ArrayList;
import java.util.List;
/**
* Graph algorithms.
*/
public class GraphUtils {
/**
* Find all paths between two nodes using DFS.
*
* @param graph Adjacency matrix representation
* @param start Starting node
* @param end Ending node
* @return List of all paths (each path is a list of nodes)
*/
public static List<List<Integer>> findAllPaths(int[][] graph, int start, int end) {
List<List<Integer>> allPaths = new ArrayList<>();
if (graph == null || graph.length == 0) {
return allPaths;
}
boolean[] visited = new boolean[graph.length];
List<Integer> currentPath = new ArrayList<>();
currentPath.add(start);
findPathsDFS(graph, start, end, visited, currentPath, allPaths);
return allPaths;
}
private static void findPathsDFS(int[][] graph, int current, int end,
boolean[] visited, List<Integer> currentPath,
List<List<Integer>> allPaths) {
if (current == end) {
allPaths.add(new ArrayList<>(currentPath));
return;
}
visited[current] = true;
for (int next = 0; next < graph.length; next++) {
if (graph[current][next] != 0 && !visited[next]) {
currentPath.add(next);
findPathsDFS(graph, next, end, visited, currentPath, allPaths);
currentPath.remove(currentPath.size() - 1);
}
}
visited[current] = false;
}
/**
* Check if graph has a cycle using DFS.
*
* @param graph Adjacency matrix
* @return true if graph has a cycle
*/
public static boolean hasCycle(int[][] graph) {
if (graph == null || graph.length == 0) {
return false;
}
int n = graph.length;
for (int start = 0; start < n; start++) {
boolean[] visited = new boolean[n];
if (hasCycleDFS(graph, start, -1, visited)) {
return true;
}
}
return false;
}
private static boolean hasCycleDFS(int[][] graph, int node, int parent, boolean[] visited) {
visited[node] = true;
for (int neighbor = 0; neighbor < graph.length; neighbor++) {
if (graph[node][neighbor] != 0) {
if (!visited[neighbor]) {
if (hasCycleDFS(graph, neighbor, node, visited)) {
return true;
}
} else if (neighbor != parent) {
return true;
}
}
}
return false;
}
/**
* Count connected components using DFS.
*
* @param graph Adjacency matrix
* @return Number of connected components
*/
public static int countComponents(int[][] graph) {
if (graph == null || graph.length == 0) {
return 0;
}
int n = graph.length;
boolean[] visited = new boolean[n];
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfsVisit(graph, i, visited);
count++;
}
}
return count;
}
private static void dfsVisit(int[][] graph, int node, boolean[] visited) {
visited[node] = true;
for (int neighbor = 0; neighbor < graph.length; neighbor++) {
if (graph[node][neighbor] != 0 && !visited[neighbor]) {
dfsVisit(graph, neighbor, visited);
}
}
}
/**
* Find shortest path using BFS.
*
* @param graph Adjacency matrix
* @param start Starting node
* @param end Ending node
* @return Shortest path length, or -1 if no path
*/
public static int shortestPath(int[][] graph, int start, int end) {
if (graph == null || graph.length == 0) {
return -1;
}
if (start == end) {
return 0;
}
int n = graph.length;
boolean[] visited = new boolean[n];
List<Integer> queue = new ArrayList<>();
int[] distance = new int[n];
queue.add(start);
visited[start] = true;
distance[start] = 0;
while (!queue.isEmpty()) {
int current = queue.remove(0);
for (int neighbor = 0; neighbor < n; neighbor++) {
if (graph[current][neighbor] != 0 && !visited[neighbor]) {
visited[neighbor] = true;
distance[neighbor] = distance[current] + 1;
if (neighbor == end) {
return distance[neighbor];
}
queue.add(neighbor);
}
}
}
return -1;
}
/**
* Check if graph is bipartite using coloring.
*
* @param graph Adjacency matrix
* @return true if bipartite
*/
public static boolean isBipartite(int[][] graph) {
if (graph == null || graph.length == 0) {
return true;
}
int n = graph.length;
int[] colors = new int[n];
for (int i = 0; i < n; i++) {
colors[i] = -1;
}
for (int start = 0; start < n; start++) {
if (colors[start] == -1) {
List<Integer> queue = new ArrayList<>();
queue.add(start);
colors[start] = 0;
while (!queue.isEmpty()) {
int node = queue.remove(0);
for (int neighbor = 0; neighbor < n; neighbor++) {
if (graph[node][neighbor] != 0) {
if (colors[neighbor] == -1) {
colors[neighbor] = 1 - colors[node];
queue.add(neighbor);
} else if (colors[neighbor] == colors[node]) {
return false;
}
}
}
}
}
}
return true;
}
/**
* Calculate in-degree of each node.
*
* @param graph Adjacency matrix
* @return Array of in-degrees
*/
public static int[] calculateInDegrees(int[][] graph) {
if (graph == null || graph.length == 0) {
return new int[0];
}
int n = graph.length;
int[] inDegree = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (graph[i][j] != 0) {
inDegree[j]++;
}
}
}
return inDegree;
}
/**
* Calculate out-degree of each node.
*
* @param graph Adjacency matrix
* @return Array of out-degrees
*/
public static int[] calculateOutDegrees(int[][] graph) {
if (graph == null || graph.length == 0) {
return new int[0];
}
int n = graph.length;
int[] outDegree = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (graph[i][j] != 0) {
outDegree[i]++;
}
}
}
return outDegree;
}
/**
* Find all nodes reachable from a given node.
*
* @param graph Adjacency matrix
* @param start Starting node
* @return List of reachable nodes
*/
public static List<Integer> findReachableNodes(int[][] graph, int start) {
List<Integer> reachable = new ArrayList<>();
if (graph == null || graph.length == 0 || start < 0 || start >= graph.length) {
return reachable;
}
boolean[] visited = new boolean[graph.length];
dfsCollect(graph, start, visited, reachable);
return reachable;
}
private static void dfsCollect(int[][] graph, int node, boolean[] visited, List<Integer> result) {
visited[node] = true;
result.add(node);
for (int neighbor = 0; neighbor < graph.length; neighbor++) {
if (graph[node][neighbor] != 0 && !visited[neighbor]) {
dfsCollect(graph, neighbor, visited, result);
}
}
}
/**
* Convert adjacency matrix to edge list.
*
* @param graph Adjacency matrix
* @return List of edges as [from, to, weight]
*/
public static List<int[]> toEdgeList(int[][] graph) {
List<int[]> edges = new ArrayList<>();
if (graph == null || graph.length == 0) {
return edges;
}
for (int i = 0; i < graph.length; i++) {
for (int j = 0; j < graph[i].length; j++) {
if (graph[i][j] != 0) {
edges.add(new int[]{i, j, graph[i][j]});
}
}
}
return edges;
}
}

View file

@ -0,0 +1,157 @@
package com.example;
/**
* Math utility functions.
*/
public class MathHelpers {
/**
* Calculate the sum of all elements in an array.
*
* @param arr Array of doubles to sum
* @return Sum of all elements
*/
public static double sumArray(double[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
/**
* Calculate the average of all elements in an array.
*
* @param arr Array of doubles
* @return Average value
*/
public static double average(double[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum / arr.length;
}
/**
* Find the maximum value in an array.
*
* @param arr Array of doubles
* @return Maximum value
*/
public static double findMax(double[] arr) {
if (arr == null || arr.length == 0) {
return Double.MIN_VALUE;
}
double max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
/**
* Find the minimum value in an array.
*
* @param arr Array of doubles
* @return Minimum value
*/
public static double findMin(double[] arr) {
if (arr == null || arr.length == 0) {
return Double.MAX_VALUE;
}
double min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
/**
* Calculate factorial using recursion.
*
* @param n Non-negative integer
* @return n factorial (n!)
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial not defined for negative numbers");
}
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
/**
* Calculate power using repeated multiplication.
*
* @param base The base number
* @param exponent The exponent (non-negative)
* @return base raised to the power of exponent
*/
public static double power(double base, int exponent) {
if (exponent < 0) {
return 1.0 / power(base, -exponent);
}
if (exponent == 0) {
return 1;
}
double result = 1;
for (int i = 0; i < exponent; i++) {
result = result * base;
}
return result;
}
/**
* Check if a number is prime using trial division.
*
* @param n Number to check
* @return true if n is prime
*/
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
/**
* Calculate greatest common divisor.
*
* @param a First number
* @param b Second number
* @return GCD of a and b
*/
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
if (a == 0) return b;
if (b == 0) return a;
int smaller = Math.min(a, b);
int gcd = 1;
for (int i = 1; i <= smaller; i++) {
if (a % i == 0 && b % i == 0) {
gcd = i;
}
}
return gcd;
}
}

View file

@ -0,0 +1,348 @@
package com.example;
/**
* Matrix operations.
*/
public class MatrixUtils {
/**
* Multiply two matrices.
*
* @param a First matrix
* @param b Second matrix
* @return Product matrix
*/
public static int[][] multiply(int[][] a, int[][] b) {
if (a == null || b == null || a.length == 0 || b.length == 0) {
return new int[0][0];
}
int rowsA = a.length;
int colsA = a[0].length;
int colsB = b[0].length;
if (colsA != b.length) {
throw new IllegalArgumentException("Matrix dimensions don't match");
}
int[][] result = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
int sum = 0;
for (int k = 0; k < colsA; k++) {
sum = sum + a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
/**
* Transpose a matrix.
*
* @param matrix Input matrix
* @return Transposed matrix
*/
public static int[][] transpose(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new int[0][0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
/**
* Add two matrices element by element.
*
* @param a First matrix
* @param b Second matrix
* @return Sum matrix
*/
public static int[][] add(int[][] a, int[][] b) {
if (a == null || b == null) {
return new int[0][0];
}
if (a.length != b.length || a[0].length != b[0].length) {
throw new IllegalArgumentException("Matrix dimensions must match");
}
int rows = a.length;
int cols = a[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
/**
* Multiply matrix by scalar.
*
* @param matrix Input matrix
* @param scalar Scalar value
* @return Scaled matrix
*/
public static int[][] scalarMultiply(int[][] matrix, int scalar) {
if (matrix == null || matrix.length == 0) {
return new int[0][0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix[i][j] * scalar;
}
}
return result;
}
/**
* Calculate determinant using recursive expansion.
*
* @param matrix Square matrix
* @return Determinant value
*/
public static long determinant(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int n = matrix.length;
if (n == 1) {
return matrix[0][0];
}
if (n == 2) {
return (long) matrix[0][0] * matrix[1][1] - (long) matrix[0][1] * matrix[1][0];
}
long det = 0;
for (int j = 0; j < n; j++) {
int[][] subMatrix = new int[n - 1][n - 1];
for (int row = 1; row < n; row++) {
int subCol = 0;
for (int col = 0; col < n; col++) {
if (col != j) {
subMatrix[row - 1][subCol] = matrix[row][col];
subCol++;
}
}
}
int sign = (j % 2 == 0) ? 1 : -1;
det = det + sign * matrix[0][j] * determinant(subMatrix);
}
return det;
}
/**
* Rotate matrix 90 degrees clockwise.
*
* @param matrix Input matrix
* @return Rotated matrix
*/
public static int[][] rotate90Clockwise(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new int[0][0];
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][rows - 1 - i] = matrix[i][j];
}
}
return result;
}
/**
* Check if matrix is symmetric.
*
* @param matrix Input matrix
* @return true if symmetric
*/
public static boolean isSymmetric(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return true;
}
int n = matrix.length;
if (n != matrix[0].length) {
return false;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] != matrix[j][i]) {
return false;
}
}
}
return true;
}
/**
* Find row with maximum sum.
*
* @param matrix Input matrix
* @return Index of row with maximum sum
*/
public static int rowWithMaxSum(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return -1;
}
int maxRow = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < matrix.length; i++) {
int sum = 0;
for (int j = 0; j < matrix[i].length; j++) {
sum = sum + matrix[i][j];
}
if (sum > maxSum) {
maxSum = sum;
maxRow = i;
}
}
return maxRow;
}
/**
* Search for element in matrix.
*
* @param matrix Input matrix
* @param target Value to find
* @return Array [row, col] or null if not found
*/
public static int[] searchElement(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0) {
return null;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
/**
* Calculate trace (sum of diagonal elements).
*
* @param matrix Square matrix
* @return Trace value
*/
public static int trace(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int sum = 0;
int n = Math.min(matrix.length, matrix[0].length);
for (int i = 0; i < n; i++) {
sum = sum + matrix[i][i];
}
return sum;
}
/**
* Create identity matrix of given size.
*
* @param n Size of matrix
* @return Identity matrix
*/
public static int[][] identity(int n) {
if (n <= 0) {
return new int[0][0];
}
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
result[i][j] = 1;
} else {
result[i][j] = 0;
}
}
}
return result;
}
/**
* Raise matrix to a power using repeated multiplication.
*
* @param matrix Square matrix
* @param power Exponent
* @return Matrix raised to power
*/
public static int[][] power(int[][] matrix, int power) {
if (matrix == null || matrix.length == 0 || power < 0) {
return new int[0][0];
}
int n = matrix.length;
if (power == 0) {
return identity(n);
}
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix[i][j];
}
}
for (int p = 1; p < power; p++) {
result = multiply(result, matrix);
}
return result;
}
}

View file

@ -0,0 +1,229 @@
package com.example;
import java.util.ArrayList;
import java.util.List;
/**
* String utility functions.
*/
public class StringUtils {
/**
* Reverse a string character by character.
*
* @param s String to reverse
* @return Reversed string
*/
public static String reverseString(String s) {
if (s == null || s.isEmpty()) {
return s;
}
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result = result + s.charAt(i);
}
return result;
}
/**
* Check if a string is a palindrome.
*
* @param s String to check
* @return true if s is a palindrome
*/
public static boolean isPalindrome(String s) {
if (s == null || s.isEmpty()) {
return true;
}
String reversed = reverseString(s);
return s.equals(reversed);
}
/**
* Count the number of words in a string.
*
* @param s String to count words in
* @return Number of words
*/
public static int countWords(String s) {
if (s == null || s.trim().isEmpty()) {
return 0;
}
String[] words = s.trim().split("\\s+");
return words.length;
}
/**
* Capitalize the first letter of each word.
*
* @param s String to capitalize
* @return String with each word capitalized
*/
public static String capitalizeWords(String s) {
if (s == null || s.isEmpty()) {
return s;
}
String[] words = s.split(" ");
String result = "";
for (int i = 0; i < words.length; i++) {
if (words[i].length() > 0) {
String capitalized = words[i].substring(0, 1).toUpperCase()
+ words[i].substring(1).toLowerCase();
result = result + capitalized;
}
if (i < words.length - 1) {
result = result + " ";
}
}
return result;
}
/**
* Count occurrences of a substring in a string.
*
* @param s String to search in
* @param sub Substring to count
* @return Number of occurrences
*/
public static int countOccurrences(String s, String sub) {
if (s == null || sub == null || sub.isEmpty()) {
return 0;
}
int count = 0;
int index = 0;
while ((index = s.indexOf(sub, index)) != -1) {
count++;
index = index + 1;
}
return count;
}
/**
* Remove all whitespace from a string.
*
* @param s String to process
* @return String without whitespace
*/
public static String removeWhitespace(String s) {
if (s == null || s.isEmpty()) {
return s;
}
String result = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c)) {
result = result + c;
}
}
return result;
}
/**
* Find all indices where a character appears in a string.
*
* @param s String to search
* @param c Character to find
* @return List of indices where character appears
*/
public static List<Integer> findAllIndices(String s, char c) {
List<Integer> indices = new ArrayList<>();
if (s == null || s.isEmpty()) {
return indices;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
indices.add(i);
}
}
return indices;
}
/**
* Check if a string contains only digits.
*
* @param s String to check
* @return true if string contains only digits
*/
public static boolean isNumeric(String s) {
if (s == null || s.isEmpty()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
/**
* Repeat a string n times.
*
* @param s String to repeat
* @param n Number of times to repeat
* @return Repeated string
*/
public static String repeat(String s, int n) {
if (s == null || n <= 0) {
return "";
}
String result = "";
for (int i = 0; i < n; i++) {
result = result + s;
}
return result;
}
/**
* Truncate a string to a maximum length with ellipsis.
*
* @param s String to truncate
* @param maxLength Maximum length (including ellipsis)
* @return Truncated string
*/
public static String truncate(String s, int maxLength) {
if (s == null || maxLength <= 0) {
return "";
}
if (s.length() <= maxLength) {
return s;
}
if (maxLength <= 3) {
return s.substring(0, maxLength);
}
return s.substring(0, maxLength - 3) + "...";
}
/**
* Convert a string to title case.
*
* @param s String to convert
* @return Title case string
*/
public static String toTitleCase(String s) {
if (s == null || s.isEmpty()) {
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
}

View file

@ -0,0 +1,87 @@
package com.example;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ArrayUtilsTest {
@Test
void testFindDuplicates() {
List<Integer> result = ArrayUtils.findDuplicates(new int[]{1, 2, 3, 2, 4, 3, 5});
assertEquals(2, result.size());
assertTrue(result.contains(2));
assertTrue(result.contains(3));
}
@Test
void testFindDuplicatesNoDuplicates() {
List<Integer> result = ArrayUtils.findDuplicates(new int[]{1, 2, 3, 4, 5});
assertTrue(result.isEmpty());
}
@Test
void testRemoveDuplicates() {
int[] result = ArrayUtils.removeDuplicates(new int[]{1, 2, 2, 3, 3, 3, 4});
assertArrayEquals(new int[]{1, 2, 3, 4}, result);
}
@Test
void testLinearSearch() {
assertEquals(2, ArrayUtils.linearSearch(new int[]{10, 20, 30, 40}, 30));
assertEquals(-1, ArrayUtils.linearSearch(new int[]{10, 20, 30, 40}, 50));
assertEquals(-1, ArrayUtils.linearSearch(null, 10));
}
@Test
void testFindIntersection() {
int[] result = ArrayUtils.findIntersection(new int[]{1, 2, 3, 4}, new int[]{3, 4, 5, 6});
assertArrayEquals(new int[]{3, 4}, result);
}
@Test
void testFindUnion() {
int[] result = ArrayUtils.findUnion(new int[]{1, 2, 3}, new int[]{3, 4, 5});
assertEquals(5, result.length);
}
@Test
void testReverseArray() {
assertArrayEquals(new int[]{5, 4, 3, 2, 1}, ArrayUtils.reverseArray(new int[]{1, 2, 3, 4, 5}));
assertArrayEquals(new int[]{1}, ArrayUtils.reverseArray(new int[]{1}));
}
@Test
void testRotateRight() {
assertArrayEquals(new int[]{4, 5, 1, 2, 3}, ArrayUtils.rotateRight(new int[]{1, 2, 3, 4, 5}, 2));
assertArrayEquals(new int[]{1, 2, 3}, ArrayUtils.rotateRight(new int[]{1, 2, 3}, 0));
}
@Test
void testCountOccurrences() {
int[][] result = ArrayUtils.countOccurrences(new int[]{1, 2, 2, 3, 3, 3});
assertEquals(3, result.length);
}
@Test
void testKthSmallest() {
assertEquals(1, ArrayUtils.kthSmallest(new int[]{3, 1, 4, 1, 5, 9, 2, 6}, 1));
assertEquals(2, ArrayUtils.kthSmallest(new int[]{3, 1, 4, 1, 5, 9, 2, 6}, 3));
assertEquals(9, ArrayUtils.kthSmallest(new int[]{3, 1, 4, 1, 5, 9, 2, 6}, 8));
}
@Test
void testFindSubarray() {
assertEquals(2, ArrayUtils.findSubarray(new int[]{1, 2, 3, 4, 5}, new int[]{3, 4}));
assertEquals(-1, ArrayUtils.findSubarray(new int[]{1, 2, 3}, new int[]{4, 5}));
assertEquals(0, ArrayUtils.findSubarray(new int[]{1, 2, 3}, new int[]{}));
}
@Test
void testMergeSortedArrays() {
assertArrayEquals(
new int[]{1, 2, 3, 4, 5, 6},
ArrayUtils.mergeSortedArrays(new int[]{1, 3, 5}, new int[]{2, 4, 6})
);
}
}

View file

@ -0,0 +1,74 @@
package com.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for BubbleSort sorting algorithms.
*/
class BubbleSortTest {
@Test
void testBubbleSort() {
assertArrayEquals(new int[]{1, 2, 3, 4, 5}, BubbleSort.bubbleSort(new int[]{5, 3, 1, 4, 2}));
assertArrayEquals(new int[]{1, 2, 3}, BubbleSort.bubbleSort(new int[]{3, 2, 1}));
assertArrayEquals(new int[]{1}, BubbleSort.bubbleSort(new int[]{1}));
assertArrayEquals(new int[]{}, BubbleSort.bubbleSort(new int[]{}));
assertNull(BubbleSort.bubbleSort(null));
}
@Test
void testBubbleSortAlreadySorted() {
assertArrayEquals(new int[]{1, 2, 3, 4, 5}, BubbleSort.bubbleSort(new int[]{1, 2, 3, 4, 5}));
}
@Test
void testBubbleSortWithDuplicates() {
assertArrayEquals(new int[]{1, 2, 2, 3, 3, 4}, BubbleSort.bubbleSort(new int[]{3, 2, 4, 1, 3, 2}));
}
@Test
void testBubbleSortWithNegatives() {
assertArrayEquals(new int[]{-5, -2, 0, 3, 7}, BubbleSort.bubbleSort(new int[]{3, -2, 7, 0, -5}));
}
@Test
void testBubbleSortDescending() {
assertArrayEquals(new int[]{5, 4, 3, 2, 1}, BubbleSort.bubbleSortDescending(new int[]{1, 3, 5, 2, 4}));
assertArrayEquals(new int[]{3, 2, 1}, BubbleSort.bubbleSortDescending(new int[]{1, 2, 3}));
assertArrayEquals(new int[]{}, BubbleSort.bubbleSortDescending(new int[]{}));
}
@Test
void testInsertionSort() {
assertArrayEquals(new int[]{1, 2, 3, 4, 5}, BubbleSort.insertionSort(new int[]{5, 3, 1, 4, 2}));
assertArrayEquals(new int[]{1, 2, 3}, BubbleSort.insertionSort(new int[]{3, 2, 1}));
assertArrayEquals(new int[]{1}, BubbleSort.insertionSort(new int[]{1}));
assertArrayEquals(new int[]{}, BubbleSort.insertionSort(new int[]{}));
}
@Test
void testSelectionSort() {
assertArrayEquals(new int[]{1, 2, 3, 4, 5}, BubbleSort.selectionSort(new int[]{5, 3, 1, 4, 2}));
assertArrayEquals(new int[]{1, 2, 3}, BubbleSort.selectionSort(new int[]{3, 2, 1}));
assertArrayEquals(new int[]{1}, BubbleSort.selectionSort(new int[]{1}));
}
@Test
void testIsSorted() {
assertTrue(BubbleSort.isSorted(new int[]{1, 2, 3, 4, 5}));
assertTrue(BubbleSort.isSorted(new int[]{1}));
assertTrue(BubbleSort.isSorted(new int[]{}));
assertTrue(BubbleSort.isSorted(null));
assertFalse(BubbleSort.isSorted(new int[]{5, 3, 1}));
assertFalse(BubbleSort.isSorted(new int[]{1, 3, 2}));
}
@Test
void testBubbleSortDoesNotMutateInput() {
int[] original = {5, 3, 1, 4, 2};
int[] copy = {5, 3, 1, 4, 2};
BubbleSort.bubbleSort(original);
assertArrayEquals(copy, original);
}
}

View file

@ -0,0 +1,133 @@
package com.example;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for Calculator statistics class.
*/
class CalculatorTest {
@Test
void testCalculateStats() {
Map<String, Double> stats = Calculator.calculateStats(new double[]{1, 2, 3, 4, 5});
assertEquals(15.0, stats.get("sum"));
assertEquals(3.0, stats.get("average"));
assertEquals(1.0, stats.get("min"));
assertEquals(5.0, stats.get("max"));
assertEquals(4.0, stats.get("range"));
}
@Test
void testCalculateStatsEmpty() {
Map<String, Double> stats = Calculator.calculateStats(new double[]{});
assertEquals(0.0, stats.get("sum"));
assertEquals(0.0, stats.get("average"));
assertEquals(0.0, stats.get("min"));
assertEquals(0.0, stats.get("max"));
assertEquals(0.0, stats.get("range"));
}
@Test
void testCalculateStatsNull() {
Map<String, Double> stats = Calculator.calculateStats(null);
assertEquals(0.0, stats.get("sum"));
assertEquals(0.0, stats.get("average"));
}
@Test
void testNormalizeArray() {
double[] result = Calculator.normalizeArray(new double[]{0, 50, 100});
assertEquals(3, result.length);
assertEquals(0.0, result[0], 0.0001);
assertEquals(0.5, result[1], 0.0001);
assertEquals(1.0, result[2], 0.0001);
}
@Test
void testNormalizeArraySameValues() {
double[] result = Calculator.normalizeArray(new double[]{5, 5, 5});
assertEquals(3, result.length);
assertEquals(0.5, result[0], 0.0001);
assertEquals(0.5, result[1], 0.0001);
assertEquals(0.5, result[2], 0.0001);
}
@Test
void testNormalizeArrayEmpty() {
double[] result = Calculator.normalizeArray(new double[]{});
assertEquals(0, result.length);
}
@Test
void testWeightedAverage() {
assertEquals(2.5, Calculator.weightedAverage(
new double[]{1, 2, 3, 4},
new double[]{1, 1, 1, 1}), 0.0001);
assertEquals(4.0, Calculator.weightedAverage(
new double[]{1, 2, 3, 4},
new double[]{0, 0, 0, 1}), 0.0001);
assertEquals(2.0, Calculator.weightedAverage(
new double[]{1, 3},
new double[]{1, 1}), 0.0001);
}
@Test
void testWeightedAverageEmpty() {
assertEquals(0.0, Calculator.weightedAverage(new double[]{}, new double[]{}));
assertEquals(0.0, Calculator.weightedAverage(null, null));
}
@Test
void testWeightedAverageMismatchedArrays() {
assertEquals(0.0, Calculator.weightedAverage(
new double[]{1, 2, 3},
new double[]{1, 1}));
}
@Test
void testVariance() {
assertEquals(2.0, Calculator.variance(new double[]{1, 2, 3, 4, 5}), 0.0001);
assertEquals(0.0, Calculator.variance(new double[]{5, 5, 5}), 0.0001);
assertEquals(0.0, Calculator.variance(new double[]{}));
}
@Test
void testStandardDeviation() {
assertEquals(Math.sqrt(2.0), Calculator.standardDeviation(new double[]{1, 2, 3, 4, 5}), 0.0001);
assertEquals(0.0, Calculator.standardDeviation(new double[]{5, 5, 5}), 0.0001);
}
@Test
void testMedian() {
assertEquals(3.0, Calculator.median(new double[]{1, 2, 3, 4, 5}), 0.0001);
assertEquals(2.5, Calculator.median(new double[]{1, 2, 3, 4}), 0.0001);
assertEquals(5.0, Calculator.median(new double[]{5}), 0.0001);
assertEquals(0.0, Calculator.median(new double[]{}));
}
@Test
void testPercentile() {
double[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assertEquals(1, Calculator.percentile(data, 0), 0.0001);
assertEquals(5, Calculator.percentile(data, 50), 0.0001);
assertEquals(10, Calculator.percentile(data, 100), 0.0001);
}
@Test
void testPercentileInvalidRange() {
assertThrows(IllegalArgumentException.class, () ->
Calculator.percentile(new double[]{1, 2, 3}, -1));
assertThrows(IllegalArgumentException.class, () ->
Calculator.percentile(new double[]{1, 2, 3}, 101));
}
}

View file

@ -0,0 +1,139 @@
package com.example;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for Fibonacci functions.
*/
class FibonacciTest {
@Test
void testFibonacci() {
assertEquals(0, Fibonacci.fibonacci(0));
assertEquals(1, Fibonacci.fibonacci(1));
assertEquals(1, Fibonacci.fibonacci(2));
assertEquals(2, Fibonacci.fibonacci(3));
assertEquals(3, Fibonacci.fibonacci(4));
assertEquals(5, Fibonacci.fibonacci(5));
assertEquals(8, Fibonacci.fibonacci(6));
assertEquals(13, Fibonacci.fibonacci(7));
assertEquals(21, Fibonacci.fibonacci(8));
assertEquals(55, Fibonacci.fibonacci(10));
}
@Test
void testFibonacciNegative() {
assertThrows(IllegalArgumentException.class, () -> Fibonacci.fibonacci(-1));
}
@Test
void testIsFibonacci() {
assertTrue(Fibonacci.isFibonacci(0));
assertTrue(Fibonacci.isFibonacci(1));
assertTrue(Fibonacci.isFibonacci(2));
assertTrue(Fibonacci.isFibonacci(3));
assertTrue(Fibonacci.isFibonacci(5));
assertTrue(Fibonacci.isFibonacci(8));
assertTrue(Fibonacci.isFibonacci(13));
assertTrue(Fibonacci.isFibonacci(21));
assertFalse(Fibonacci.isFibonacci(4));
assertFalse(Fibonacci.isFibonacci(6));
assertFalse(Fibonacci.isFibonacci(7));
assertFalse(Fibonacci.isFibonacci(9));
assertFalse(Fibonacci.isFibonacci(-1));
}
@Test
void testIsPerfectSquare() {
assertTrue(Fibonacci.isPerfectSquare(0));
assertTrue(Fibonacci.isPerfectSquare(1));
assertTrue(Fibonacci.isPerfectSquare(4));
assertTrue(Fibonacci.isPerfectSquare(9));
assertTrue(Fibonacci.isPerfectSquare(16));
assertTrue(Fibonacci.isPerfectSquare(25));
assertTrue(Fibonacci.isPerfectSquare(100));
assertFalse(Fibonacci.isPerfectSquare(2));
assertFalse(Fibonacci.isPerfectSquare(3));
assertFalse(Fibonacci.isPerfectSquare(5));
assertFalse(Fibonacci.isPerfectSquare(-1));
}
@Test
void testFibonacciSequence() {
assertArrayEquals(new long[]{}, Fibonacci.fibonacciSequence(0));
assertArrayEquals(new long[]{0}, Fibonacci.fibonacciSequence(1));
assertArrayEquals(new long[]{0, 1}, Fibonacci.fibonacciSequence(2));
assertArrayEquals(new long[]{0, 1, 1, 2, 3}, Fibonacci.fibonacciSequence(5));
assertArrayEquals(new long[]{0, 1, 1, 2, 3, 5, 8, 13, 21, 34}, Fibonacci.fibonacciSequence(10));
}
@Test
void testFibonacciSequenceNegative() {
assertThrows(IllegalArgumentException.class, () -> Fibonacci.fibonacciSequence(-1));
}
@Test
void testFibonacciIndex() {
assertEquals(0, Fibonacci.fibonacciIndex(0));
assertEquals(1, Fibonacci.fibonacciIndex(1));
assertEquals(3, Fibonacci.fibonacciIndex(2));
assertEquals(4, Fibonacci.fibonacciIndex(3));
assertEquals(5, Fibonacci.fibonacciIndex(5));
assertEquals(6, Fibonacci.fibonacciIndex(8));
assertEquals(7, Fibonacci.fibonacciIndex(13));
assertEquals(-1, Fibonacci.fibonacciIndex(4));
assertEquals(-1, Fibonacci.fibonacciIndex(6));
assertEquals(-1, Fibonacci.fibonacciIndex(-1));
}
@Test
void testSumFibonacci() {
assertEquals(0, Fibonacci.sumFibonacci(0));
assertEquals(0, Fibonacci.sumFibonacci(1));
assertEquals(1, Fibonacci.sumFibonacci(2));
assertEquals(2, Fibonacci.sumFibonacci(3));
assertEquals(4, Fibonacci.sumFibonacci(4));
assertEquals(7, Fibonacci.sumFibonacci(5));
assertEquals(12, Fibonacci.sumFibonacci(6));
}
@Test
void testFibonacciUpTo() {
List<Long> result = Fibonacci.fibonacciUpTo(10);
assertEquals(7, result.size());
assertEquals(0L, result.get(0));
assertEquals(1L, result.get(1));
assertEquals(1L, result.get(2));
assertEquals(2L, result.get(3));
assertEquals(3L, result.get(4));
assertEquals(5L, result.get(5));
assertEquals(8L, result.get(6));
}
@Test
void testFibonacciUpToZero() {
List<Long> result = Fibonacci.fibonacciUpTo(0);
assertTrue(result.isEmpty());
}
@Test
void testAreConsecutiveFibonacci() {
// Test consecutive Fibonacci pairs (from index 3 onwards to avoid ambiguity with 1,1)
assertTrue(Fibonacci.areConsecutiveFibonacci(2, 3)); // indices 3 and 4
assertTrue(Fibonacci.areConsecutiveFibonacci(3, 5)); // indices 4 and 5
assertTrue(Fibonacci.areConsecutiveFibonacci(5, 8)); // indices 5 and 6
assertTrue(Fibonacci.areConsecutiveFibonacci(8, 13)); // indices 6 and 7
// Non-consecutive Fibonacci pairs
assertFalse(Fibonacci.areConsecutiveFibonacci(2, 5)); // indices 3 and 5
assertFalse(Fibonacci.areConsecutiveFibonacci(3, 8)); // indices 4 and 6
// Non-Fibonacci number
assertFalse(Fibonacci.areConsecutiveFibonacci(4, 5)); // 4 is not Fibonacci
}
}

View file

@ -0,0 +1,136 @@
package com.example;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class GraphUtilsTest {
@Test
void testFindAllPaths() {
int[][] graph = {
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
List<List<Integer>> paths = GraphUtils.findAllPaths(graph, 0, 3);
assertEquals(3, paths.size());
}
@Test
void testHasCycle() {
int[][] cyclicGraph = {
{0, 1, 0},
{0, 0, 1},
{1, 0, 0}
};
assertTrue(GraphUtils.hasCycle(cyclicGraph));
int[][] acyclicGraph = {
{0, 1, 0},
{0, 0, 1},
{0, 0, 0}
};
assertFalse(GraphUtils.hasCycle(acyclicGraph));
}
@Test
void testCountComponents() {
int[][] graph = {
{0, 1, 0, 0},
{1, 0, 0, 0},
{0, 0, 0, 1},
{0, 0, 1, 0}
};
assertEquals(2, GraphUtils.countComponents(graph));
}
@Test
void testShortestPath() {
int[][] graph = {
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
assertEquals(3, GraphUtils.shortestPath(graph, 0, 3));
assertEquals(0, GraphUtils.shortestPath(graph, 0, 0));
assertEquals(-1, GraphUtils.shortestPath(graph, 3, 0));
}
@Test
void testIsBipartite() {
int[][] bipartite = {
{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};
assertTrue(GraphUtils.isBipartite(bipartite));
int[][] notBipartite = {
{0, 1, 1},
{1, 0, 1},
{1, 1, 0}
};
assertFalse(GraphUtils.isBipartite(notBipartite));
}
@Test
void testCalculateInDegrees() {
int[][] graph = {
{0, 1, 1},
{0, 0, 1},
{0, 0, 0}
};
int[] inDegrees = GraphUtils.calculateInDegrees(graph);
assertEquals(0, inDegrees[0]);
assertEquals(1, inDegrees[1]);
assertEquals(2, inDegrees[2]);
}
@Test
void testCalculateOutDegrees() {
int[][] graph = {
{0, 1, 1},
{0, 0, 1},
{0, 0, 0}
};
int[] outDegrees = GraphUtils.calculateOutDegrees(graph);
assertEquals(2, outDegrees[0]);
assertEquals(1, outDegrees[1]);
assertEquals(0, outDegrees[2]);
}
@Test
void testFindReachableNodes() {
int[][] graph = {
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
List<Integer> reachable = GraphUtils.findReachableNodes(graph, 0);
assertEquals(3, reachable.size());
assertTrue(reachable.contains(0));
assertTrue(reachable.contains(1));
assertTrue(reachable.contains(2));
}
@Test
void testToEdgeList() {
int[][] graph = {
{0, 1, 0},
{0, 0, 2},
{3, 0, 0}
};
List<int[]> edges = GraphUtils.toEdgeList(graph);
assertEquals(3, edges.size());
}
}

View file

@ -0,0 +1,91 @@
package com.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for MathHelpers utility class.
*/
class MathHelpersTest {
@Test
void testSumArray() {
assertEquals(10.0, MathHelpers.sumArray(new double[]{1, 2, 3, 4}));
assertEquals(0.0, MathHelpers.sumArray(new double[]{}));
assertEquals(0.0, MathHelpers.sumArray(null));
assertEquals(5.5, MathHelpers.sumArray(new double[]{5.5}));
assertEquals(-3.0, MathHelpers.sumArray(new double[]{-1, -2, 0}));
}
@Test
void testAverage() {
assertEquals(2.5, MathHelpers.average(new double[]{1, 2, 3, 4}));
assertEquals(0.0, MathHelpers.average(new double[]{}));
assertEquals(0.0, MathHelpers.average(null));
assertEquals(10.0, MathHelpers.average(new double[]{10}));
}
@Test
void testFindMax() {
assertEquals(4.0, MathHelpers.findMax(new double[]{1, 2, 3, 4}));
assertEquals(-1.0, MathHelpers.findMax(new double[]{-5, -1, -10}));
assertEquals(5.0, MathHelpers.findMax(new double[]{5}));
}
@Test
void testFindMin() {
assertEquals(1.0, MathHelpers.findMin(new double[]{1, 2, 3, 4}));
assertEquals(-10.0, MathHelpers.findMin(new double[]{-5, -1, -10}));
assertEquals(5.0, MathHelpers.findMin(new double[]{5}));
}
@Test
void testFactorial() {
assertEquals(1, MathHelpers.factorial(0));
assertEquals(1, MathHelpers.factorial(1));
assertEquals(2, MathHelpers.factorial(2));
assertEquals(6, MathHelpers.factorial(3));
assertEquals(120, MathHelpers.factorial(5));
assertEquals(3628800, MathHelpers.factorial(10));
}
@Test
void testFactorialNegative() {
assertThrows(IllegalArgumentException.class, () -> MathHelpers.factorial(-1));
}
@Test
void testPower() {
assertEquals(8.0, MathHelpers.power(2, 3));
assertEquals(1.0, MathHelpers.power(5, 0));
assertEquals(1.0, MathHelpers.power(0, 0));
assertEquals(0.0, MathHelpers.power(0, 5));
assertEquals(0.5, MathHelpers.power(2, -1), 0.0001);
assertEquals(0.125, MathHelpers.power(2, -3), 0.0001);
}
@Test
void testIsPrime() {
assertFalse(MathHelpers.isPrime(0));
assertFalse(MathHelpers.isPrime(1));
assertTrue(MathHelpers.isPrime(2));
assertTrue(MathHelpers.isPrime(3));
assertFalse(MathHelpers.isPrime(4));
assertTrue(MathHelpers.isPrime(5));
assertTrue(MathHelpers.isPrime(7));
assertFalse(MathHelpers.isPrime(9));
assertTrue(MathHelpers.isPrime(11));
assertTrue(MathHelpers.isPrime(13));
assertFalse(MathHelpers.isPrime(15));
}
@Test
void testGcd() {
assertEquals(6, MathHelpers.gcd(12, 18));
assertEquals(1, MathHelpers.gcd(7, 13));
assertEquals(5, MathHelpers.gcd(0, 5));
assertEquals(5, MathHelpers.gcd(5, 0));
assertEquals(4, MathHelpers.gcd(8, 12));
assertEquals(3, MathHelpers.gcd(-9, 12));
}
}

View file

@ -0,0 +1,120 @@
package com.example;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MatrixUtilsTest {
@Test
void testMultiply() {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] result = MatrixUtils.multiply(a, b);
assertEquals(19, result[0][0]);
assertEquals(22, result[0][1]);
assertEquals(43, result[1][0]);
assertEquals(50, result[1][1]);
}
@Test
void testTranspose() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[][] result = MatrixUtils.transpose(matrix);
assertEquals(3, result.length);
assertEquals(2, result[0].length);
assertEquals(1, result[0][0]);
assertEquals(4, result[0][1]);
}
@Test
void testAdd() {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] result = MatrixUtils.add(a, b);
assertEquals(6, result[0][0]);
assertEquals(8, result[0][1]);
assertEquals(10, result[1][0]);
assertEquals(12, result[1][1]);
}
@Test
void testScalarMultiply() {
int[][] matrix = {{1, 2}, {3, 4}};
int[][] result = MatrixUtils.scalarMultiply(matrix, 3);
assertEquals(3, result[0][0]);
assertEquals(6, result[0][1]);
assertEquals(9, result[1][0]);
assertEquals(12, result[1][1]);
}
@Test
void testDeterminant() {
assertEquals(1, MatrixUtils.determinant(new int[][]{{1}}));
assertEquals(-2, MatrixUtils.determinant(new int[][]{{1, 2}, {3, 4}}));
assertEquals(0, MatrixUtils.determinant(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}));
}
@Test
void testRotate90Clockwise() {
int[][] matrix = {{1, 2}, {3, 4}};
int[][] result = MatrixUtils.rotate90Clockwise(matrix);
assertEquals(3, result[0][0]);
assertEquals(1, result[0][1]);
assertEquals(4, result[1][0]);
assertEquals(2, result[1][1]);
}
@Test
void testIsSymmetric() {
assertTrue(MatrixUtils.isSymmetric(new int[][]{{1, 2}, {2, 1}}));
assertFalse(MatrixUtils.isSymmetric(new int[][]{{1, 2}, {3, 4}}));
}
@Test
void testRowWithMaxSum() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {1, 1, 1}};
assertEquals(1, MatrixUtils.rowWithMaxSum(matrix));
}
@Test
void testSearchElement() {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[] result = MatrixUtils.searchElement(matrix, 5);
assertNotNull(result);
assertEquals(1, result[0]);
assertEquals(1, result[1]);
assertNull(MatrixUtils.searchElement(matrix, 10));
}
@Test
void testTrace() {
assertEquals(5, MatrixUtils.trace(new int[][]{{1, 2}, {3, 4}}));
assertEquals(15, MatrixUtils.trace(new int[][]{{1, 0, 0}, {0, 5, 0}, {0, 0, 9}}));
}
@Test
void testIdentity() {
int[][] result = MatrixUtils.identity(3);
assertEquals(1, result[0][0]);
assertEquals(0, result[0][1]);
assertEquals(1, result[1][1]);
assertEquals(1, result[2][2]);
}
@Test
void testPower() {
int[][] matrix = {{1, 1}, {1, 0}};
int[][] result = MatrixUtils.power(matrix, 3);
assertEquals(3, result[0][0]);
assertEquals(2, result[0][1]);
}
}

View file

@ -0,0 +1,135 @@
package com.example;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for StringUtils utility class.
*/
class StringUtilsTest {
@Test
void testReverseString() {
assertEquals("olleh", StringUtils.reverseString("hello"));
assertEquals("a", StringUtils.reverseString("a"));
assertEquals("", StringUtils.reverseString(""));
assertNull(StringUtils.reverseString(null));
assertEquals("dcba", StringUtils.reverseString("abcd"));
}
@Test
void testIsPalindrome() {
assertTrue(StringUtils.isPalindrome("racecar"));
assertTrue(StringUtils.isPalindrome("madam"));
assertTrue(StringUtils.isPalindrome("a"));
assertTrue(StringUtils.isPalindrome(""));
assertTrue(StringUtils.isPalindrome(null));
assertTrue(StringUtils.isPalindrome("abba"));
assertFalse(StringUtils.isPalindrome("hello"));
assertFalse(StringUtils.isPalindrome("ab"));
}
@Test
void testCountWords() {
assertEquals(3, StringUtils.countWords("hello world test"));
assertEquals(1, StringUtils.countWords("hello"));
assertEquals(0, StringUtils.countWords(""));
assertEquals(0, StringUtils.countWords(" "));
assertEquals(0, StringUtils.countWords(null));
assertEquals(4, StringUtils.countWords(" multiple spaces between words "));
}
@Test
void testCapitalizeWords() {
assertEquals("Hello World", StringUtils.capitalizeWords("hello world"));
assertEquals("Hello", StringUtils.capitalizeWords("HELLO"));
assertEquals("", StringUtils.capitalizeWords(""));
assertNull(StringUtils.capitalizeWords(null));
assertEquals("One Two Three", StringUtils.capitalizeWords("one two three"));
}
@Test
void testCountOccurrences() {
assertEquals(2, StringUtils.countOccurrences("hello hello", "hello"));
assertEquals(3, StringUtils.countOccurrences("aaa", "a"));
assertEquals(2, StringUtils.countOccurrences("aaa", "aa"));
assertEquals(0, StringUtils.countOccurrences("hello", "world"));
assertEquals(0, StringUtils.countOccurrences("hello", ""));
assertEquals(0, StringUtils.countOccurrences(null, "test"));
}
@Test
void testRemoveWhitespace() {
assertEquals("helloworld", StringUtils.removeWhitespace("hello world"));
assertEquals("abc", StringUtils.removeWhitespace(" a b c "));
assertEquals("test", StringUtils.removeWhitespace("test"));
assertEquals("", StringUtils.removeWhitespace(" "));
assertEquals("", StringUtils.removeWhitespace(""));
assertNull(StringUtils.removeWhitespace(null));
}
@Test
void testFindAllIndices() {
List<Integer> indices = StringUtils.findAllIndices("hello", 'l');
assertEquals(2, indices.size());
assertEquals(2, indices.get(0));
assertEquals(3, indices.get(1));
indices = StringUtils.findAllIndices("aaa", 'a');
assertEquals(3, indices.size());
indices = StringUtils.findAllIndices("hello", 'z');
assertTrue(indices.isEmpty());
indices = StringUtils.findAllIndices("", 'a');
assertTrue(indices.isEmpty());
indices = StringUtils.findAllIndices(null, 'a');
assertTrue(indices.isEmpty());
}
@Test
void testIsNumeric() {
assertTrue(StringUtils.isNumeric("12345"));
assertTrue(StringUtils.isNumeric("0"));
assertTrue(StringUtils.isNumeric("007"));
assertFalse(StringUtils.isNumeric("12.34"));
assertFalse(StringUtils.isNumeric("-123"));
assertFalse(StringUtils.isNumeric("abc"));
assertFalse(StringUtils.isNumeric("12a34"));
assertFalse(StringUtils.isNumeric(""));
assertFalse(StringUtils.isNumeric(null));
}
@Test
void testRepeat() {
assertEquals("abcabcabc", StringUtils.repeat("abc", 3));
assertEquals("aaa", StringUtils.repeat("a", 3));
assertEquals("", StringUtils.repeat("abc", 0));
assertEquals("", StringUtils.repeat("abc", -1));
assertEquals("", StringUtils.repeat(null, 3));
}
@Test
void testTruncate() {
assertEquals("hello", StringUtils.truncate("hello", 10));
assertEquals("hel...", StringUtils.truncate("hello world", 6));
assertEquals("hello...", StringUtils.truncate("hello world", 8));
assertEquals("", StringUtils.truncate("hello", 0));
assertEquals("", StringUtils.truncate(null, 10));
assertEquals("hel", StringUtils.truncate("hello", 3));
}
@Test
void testToTitleCase() {
assertEquals("Hello", StringUtils.toTitleCase("hello"));
assertEquals("Hello", StringUtils.toTitleCase("HELLO"));
assertEquals("Hello", StringUtils.toTitleCase("hELLO"));
assertEquals("A", StringUtils.toTitleCase("a"));
assertEquals("", StringUtils.toTitleCase(""));
assertNull(StringUtils.toTitleCase(null));
}
}