diff --git a/pom.xml b/pom.xml index c7d6525..a06e4a8 100644 --- a/pom.xml +++ b/pom.xml @@ -20,19 +20,20 @@ - scm:git:git://bitbucket.org/Mattrixwv/Matrix.git - scm:git:ssh://bitbucket.org:Mattrixwv/Matrix.git - https://bitbucket.org/Mattrixwv/Matrix/src + scm:git:git://bitbucket.org/Mattrixwv/JavaClasses.git + scm:git:ssh://bitbucket.org:Mattrixwv/JavaClasses.git + https://bitbucket.org/Mattrixwv/JavaClasses/src com.mattrixwv myClasses - 1.3.6-SNAPSHOT + 1.3.6 myClasses A grouping of functions that I've found useful www.mattrixwv.com + UTF-8 @@ -50,6 +51,7 @@ 3BA6515C8FF145249BEBBEABA52FDEC4259179D4 + org.junit.jupiter @@ -251,7 +253,6 @@ ${gpg.keyname} - ${gpg.keyname} diff --git a/src/main/java/com/mattrixwv/ArrayAlgorithms.java b/src/main/java/com/mattrixwv/ArrayAlgorithms.java index 8c1e606..c40c7c3 100644 --- a/src/main/java/com/mattrixwv/ArrayAlgorithms.java +++ b/src/main/java/com/mattrixwv/ArrayAlgorithms.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java //Matthew Ellison // Created: 07-03-21 -//Modified: 06-25-22 +//Modified: 08-11-24 //This class contains algorithms for vectors that I've found it useful to keep around /* - Copyright (C) 2022 Matthew Ellison + Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -28,9 +28,26 @@ import java.util.List; import java.util.StringJoiner; +/** + * The {@code ArrayAlgorithms} class provides static utility methods for performing + * arithmetic operations on collections of numbers, including integers, longs, and BigIntegers. + * It also includes utility methods for printing and converting lists. + * + *

This class is not intended to be instantiated.

+ */ public class ArrayAlgorithms{ + /** + * Private constructor to prevent instantiation of this utility class. + */ private ArrayAlgorithms(){} - //This function returns the sum of all elements in the list + + //?This function returns the sum of all elements in the list + /** + * Returns the sum of all elements in the given iterable collection of integers. + * + * @param nums the iterable collection of integers to sum + * @return the sum of all integers in the collection + */ public static int getSum(Iterable nums){ //Setup the variables int sum = 0; @@ -43,6 +60,12 @@ public class ArrayAlgorithms{ //Return the sum of all elements return sum; } + /** + * Returns the sum of all elements in the given iterable of longs. + * + * @param nums the iterable collection of longs to sum + * @return the sum of all longs in the collection + */ public static long getLongSum(Iterable nums){ //Setup the variables long sum = 0; @@ -55,6 +78,12 @@ public class ArrayAlgorithms{ //Return the sum of all elements return sum; } + /** + * Returns the sum of all elements in the given iterable collection of {@code BigInteger} objects. + * + * @param nums the iterable collection of {@code BigInteger} objects to sum + * @return the sum of all {@code BigInteger} objects in the collection + */ public static BigInteger getBigSum(Iterable nums){ //Setup the variables BigInteger sum = BigInteger.ZERO; @@ -67,7 +96,15 @@ public class ArrayAlgorithms{ //Return the sum of all elements return sum; } - //This function returns the product of all elements in the list + + //?This function returns the product of all elements in the list + /** + * Returns the product of all elements in the given iterable collection of integers. + * If the iterable is empty, it returns 0. + * + * @param nums the iterable collection of integers to multiply + * @return the product of all integers in the collection, or 0 if the collection is empty + */ public static int getProd(Iterable nums){ //If a blank list was passed tot he fuction return 0 as the product if(!nums.iterator().hasNext()){ @@ -85,6 +122,13 @@ public class ArrayAlgorithms{ //Return the product of all elements return product; } + /** + * Returns the product of all elements in the given iterable collection of longs. + * If the iterable is empty, it returns 0. + * + * @param nums the iterable collection of longs to multiply + * @return the product of all longs in the collection, or 0 if the collection is empty + */ public static long getLongProd(Iterable nums){ //If a blank list was passed tot he fuction return 0 as the product if(!nums.iterator().hasNext()){ @@ -102,6 +146,13 @@ public class ArrayAlgorithms{ //Return the product of all elements return product; } + /** + * Returns the product of all elements in the given iterable collection of {@code BigInteger} objects. + * If the collection is empty, it returns 0. + * + * @param nums the iterable collection of {@code BigInteger} objects to multiply + * @return the product of all {@code BigInteger} objects in the collection, or 0 if the collection is empty + */ public static BigInteger getBigProd(Iterable nums){ //If a blank list was passed tot he fuction return 0 as the product if(!nums.iterator().hasNext()){ @@ -119,7 +170,16 @@ public class ArrayAlgorithms{ //Return the product of all elements return product; } - //Print a list + + //?Print a list + /** + * Returns a string representation of the given iterable collection, with elements separated by commas + * and enclosed in square brackets. + * + * @param list the iterable collection to print + * @param the type of elements in the collection + * @return a string representation of the collection + */ public static String printList(Iterable list){ StringJoiner returnString = new StringJoiner(", ", "[", "]"); for(T obj : list){ @@ -127,7 +187,14 @@ public class ArrayAlgorithms{ } return returnString.toString(); } - //Convert lists + + //?Convert lists + /** + * Converts a list of {@code Long} objects to a list of {@code Integer} objects. + * + * @param originalList the list of {@code Long} objects to convert + * @return a list of {@code Integer} objects + */ public static List longToInt(List originalList){ ArrayList newList = new ArrayList<>(originalList.size()); for(Long num : originalList){ diff --git a/src/main/java/com/mattrixwv/NumberAlgorithms.java b/src/main/java/com/mattrixwv/NumberAlgorithms.java index 0b9b831..846daa6 100644 --- a/src/main/java/com/mattrixwv/NumberAlgorithms.java +++ b/src/main/java/com/mattrixwv/NumberAlgorithms.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/NumberAlgorithms.java //Matthew Ellison // Created: 07-03-21 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class contains algorithms for numbers that I've found it useful to keep around /* - Copyright (C) 2023 Matthew Ellison + Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -32,15 +32,40 @@ import java.util.List; import com.mattrixwv.exceptions.InvalidResult; +/** + * Utility class that provides a variety of number-related algorithms, + * such as prime number generation, Fibonacci number calculation, + * factorial computation, and greatest common divisor determination. + *

This class cannot be instantiated.

+ */ public class NumberAlgorithms{ + /** + * Private constructor to prevent instantiation + */ private NumberAlgorithms(){} + /** + * Error message used for invalid factorial inputs. + */ public static final String FACTORIAL_NEGATIVE_MESSAGE = "n! cannot be negative"; - //This function returns a list with all the prime numbers <= goalNumber + //?This function returns a list with all the prime numbers <= goalNumber + /** + * Returns a list of all prime numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating prime numbers + * @return a list of prime numbers less than or equal to {@code goalNumber} + * @see #getPrimes(long) + */ public static List getPrimes(int goalNumber){ return ArrayAlgorithms.longToInt(getPrimes((long) goalNumber)); } + /** + * Returns a list of all prime numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating prime numbers + * @return a list of prime numbers less than or equal to {@code goalNumber} + */ public static List getPrimes(long goalNumber){ ArrayList primes = new ArrayList<>(); //Holds the prime numbers boolean foundFactor = false; //A flag for whether a factor of the current number has been found @@ -54,7 +79,7 @@ public class NumberAlgorithms{ primes.add(2L); } - //We cna now start at 3 and skipp all even numbers, because they cannot be prime + //We can now start at 3 and skip all even numbers, because they cannot be prime for(long possiblePrime = 3L;possiblePrime <= goalNumber;possiblePrime += 2L){ //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime)); @@ -79,6 +104,12 @@ public class NumberAlgorithms{ Collections.sort(primes); return primes; } + /** + * Returns a list of all prime numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating prime numbers + * @return a list of prime numbers less than or equal to {@code goalNumber} + */ public static List getPrimes(BigInteger goalNumber){ ArrayList primes = new ArrayList<>(); //Holds the prime numbers boolean foundFactor = false; //A flag for whether a factor of the current number has been found @@ -119,10 +150,23 @@ public class NumberAlgorithms{ } - //This function gets a certain number of primes + //?This function gets a certain number of primes + /** + * Returns a list of the specified number of prime numbers. + * + * @param numberOfPrimes the number of prime numbers to generate + * @return a list containing the first {@code numberOfPrimes} prime numbers + * @see #getNumPrimes(long) + */ public static List getNumPrimes(int numberOfPrimes){ return ArrayAlgorithms.longToInt(getNumPrimes((long)numberOfPrimes)); } + /** + * Returns a list of the specified number of prime numbers. + * + * @param numberOfPrimes the number of prime numbers to generate + * @return a list containing the first {@code numberOfPrimes} prime numbers + */ public static List getNumPrimes(long numberOfPrimes){ ArrayList primes = new ArrayList<>(); //Holds the prime numbers boolean foundFactor = false; //A flag for whether a factor of the current number has been found @@ -161,6 +205,12 @@ public class NumberAlgorithms{ Collections.sort(primes); return primes; } + /** + * Returns a list of the specified number of prime numbers. + * + * @param numberOfPrimes the number of prime numbers to generate + * @return a list containing the first {@code numberOfPrimes} prime numbers + */ public static List getNumPrimes(BigInteger numberOfPrimes){ ArrayList primes = new ArrayList<>(); //Holds the prime numbers boolean foundFactor = false; //A flag for whether a factor of the current number has been found @@ -201,7 +251,13 @@ public class NumberAlgorithms{ } - //This function return true if the value passed to it is prime + //?This function return true if the value passed to it is prime + /** + * Determines if a given number is prime. + * + * @param possiblePrime the number to be checked for primality + * @return {@code true} if {@code possiblePrime} is a prime number, {@code false} otherwise + */ public static boolean isPrime(long possiblePrime){ if(possiblePrime <= 3){ return possiblePrime > 1; @@ -216,6 +272,12 @@ public class NumberAlgorithms{ } return true; } + /** + * Determines if a given number is prime. + * + * @param possiblePrime the number to be checked for primality + * @return {@code true} if {@code possiblePrime} is a prime number, {@code false} otherwise + */ public static boolean isPrime(BigInteger possiblePrime){ if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){ return possiblePrime.compareTo(BigInteger.ONE) > 0; @@ -232,10 +294,23 @@ public class NumberAlgorithms{ } - //This function returns all factors of goalNumber + //?This function returns all factors of goalNumber + /** + * Returns a list of prime factors of the specified number. + * + * @param goalNumber the number to factorize + * @return a list of prime factors of {@code goalNumber} + * @see #getFactors(long) + */ public static List getFactors(int goalNumber) throws InvalidResult{ return ArrayAlgorithms.longToInt(getFactors((long)goalNumber)); } + /** + * Returns a list of prime factors of the specified number. + * + * @param goalNumber the number to factorize + * @return a list of prime factors of {@code goalNumber} + */ public static List getFactors(long goalNumber) throws InvalidResult{ //You need to get all the primes that could be factors of this number so you can test them Double topPossiblePrime = Math.ceil(Math.sqrt(goalNumber)); @@ -270,6 +345,12 @@ public class NumberAlgorithms{ //Return the list of factors return factors; } + /** + * Returns a list of prime factors of the specified number. + * + * @param goalNumber the number to factorize + * @return a list of prime factors of {@code goalNumber} + */ public static List getFactors(BigInteger goalNumber) throws InvalidResult{ //You need to get all the primes that could be factors of this number so you can test them BigInteger topPossiblePrime = goalNumber.sqrt().add(BigInteger.ONE); @@ -306,10 +387,23 @@ public class NumberAlgorithms{ } - //This function returns all the divisors of goalNumber + //?This function returns all the divisors of goalNumber + /** + * Returns a list of divisors of the specified number. + * + * @param goalNumber the number to find divisors for + * @return a list of divisors of {@code goalNumber} + * @see #getDivisors(long) + */ public static List getDivisors(int goalNumber){ return ArrayAlgorithms.longToInt(getDivisors((long)goalNumber)); } + /** + * Returns a list of divisors of the specified number. + * + * @param goalNumber the number to find divisors for + * @return a list of divisors of {@code goalNumber} + */ public static List getDivisors(long goalNumber){ HashSet divisors = new HashSet<>(); //Start by checking that the number is positive @@ -338,6 +432,12 @@ public class NumberAlgorithms{ //Return the list return divisorList; } + /** + * Returns a list of divisors of the specified number. + * + * @param goalNumber the number to find divisors for + * @return a list of divisors of {@code goalNumber} + */ public static List getDivisors(BigInteger goalNumber){ HashSet divisors = new HashSet<>(); //Start by checking that the number is positive @@ -367,10 +467,24 @@ public class NumberAlgorithms{ return divisorList; } - //This function returns the goalSubscript'th Fibonacci number + + //?This function returns the goalSubscript'th Fibonacci number + /** + * Returns the Fibonacci number at the specified position. + * + * @param goalSubscript the position of the desired Fibonacci number + * @return the Fibonacci number at position {@code goalSubscript} + * @see #getFib(long) + */ public static int getFib(int goalSubscript){ return (int)getFib((long)goalSubscript); } + /** + * Returns the Fibonacci number at the specified position. + * + * @param goalSubscript the position of the desired Fibonacci number + * @return the Fibonacci number at position {@code goalSubscript} + */ public static long getFib(long goalSubscript){ //Setup the variables long[] fibNums = {1L, 1L, 0L}; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2 @@ -389,6 +503,12 @@ public class NumberAlgorithms{ //Return the proper number. The location counter is 1 off of the subscript return fibNums[(fibLoc - 1) % 3]; } + /** + * Returns the Fibonacci number at the specified position. + * + * @param goalSubscript the position of the desired Fibonacci number + * @return the Fibonacci number at position {@code goalSubscript} + */ public static BigInteger getFib(BigInteger goalSubscript){ //Setup the variables BigInteger[] fibNums = {BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(0)}; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2 @@ -408,10 +528,24 @@ public class NumberAlgorithms{ return fibNums[(fibLoc - 1) % 3]; } - //This function returns a list of all Fibonacci numbers <= goalNumber + + //?This function returns a list of all Fibonacci numbers <= goalNumber + /** + * Returns a list of all Fibonacci numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating Fibonacci numbers + * @return a list of Fibonacci numbers less than or equal to {@code goalNumber} + * @see #getAllFib(long) + */ public static List getAllFib(int goalNumber){ return ArrayAlgorithms.longToInt(getAllFib((long) goalNumber)); } + /** + * Returns a list of all Fibonacci numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating Fibonacci numbers + * @return a list of Fibonacci numbers less than or equal to {@code goalNumber} + */ public static List getAllFib(long goalNumber){ //Setup the variables ArrayList fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers @@ -434,6 +568,12 @@ public class NumberAlgorithms{ fibNums.remove(fibNums.size() - 1); return fibNums; } + /** + * Returns a list of all Fibonacci numbers less than or equal to the specified number. + * + * @param goalNumber the upper limit for generating Fibonacci numbers + * @return a list of Fibonacci numbers less than or equal to {@code goalNumber} + */ public static List getAllFib(BigInteger goalNumber){ //Setup the variables ArrayList fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers @@ -457,10 +597,26 @@ public class NumberAlgorithms{ return fibNums; } - //This function returns the factorial of the number passed to it + + //?This function returns the factorial of the number passed to it + /** + * Calculates the factorial of the specified number. + * + * @param goalNumber the number to calculate the factorial for + * @return the factorial of {@code goalNumber} + * @throws IllegalArgumentException if {@code goalNumber} is negative + * @see #factorial(long) + */ public static int factorial(int num) throws InvalidParameterException{ return (int)factorial((long)num); } + /** + * Calculates the factorial of the specified number. + * + * @param goalNumber the number to calculate the factorial for + * @return the factorial of {@code goalNumber} + * @throws IllegalArgumentException if {@code goalNumber} is negative + */ public static long factorial(long num) throws InvalidParameterException{ long fact = 1L; //The value of the factorial @@ -475,6 +631,13 @@ public class NumberAlgorithms{ return fact; } + /** + * Calculates the factorial of the specified number. + * + * @param goalNumber the number to calculate the factorial for + * @return the factorial of {@code goalNumber} + * @throws IllegalArgumentException if {@code goalNumber} is negative + */ public static BigInteger factorial(BigInteger num) throws InvalidParameterException{ BigInteger fact = BigInteger.valueOf(1L); @@ -490,10 +653,26 @@ public class NumberAlgorithms{ return fact; } - //This function returns the GCD of the two numbers sent to it + + //?This function returns the GCD of the two numbers sent to it + /** + * Calculates the greatest common divisor (GCD) of two numbers. + * + * @param num1 the first number + * @param num2 the second number + * @return the greatest common divisor of {@code num1} and {@code num2} + * @see #gcd(long, long) + */ public static int gcd(int num1, int num2){ return (int)gcd((long)num1, (long)num2); } + /** + * Calculates the greatest common divisor (GCD) of two numbers. + * + * @param num1 the first number + * @param num2 the second number + * @return the greatest common divisor of {@code num1} and {@code num2} + */ public static long gcd(long num1, long num2){ while((num1 != 0) && (num2 != 0)){ if(num1 > num2){ @@ -505,6 +684,13 @@ public class NumberAlgorithms{ } return num1 | num2; } + /** + * Calculates the greatest common divisor (GCD) of two numbers. + * + * @param num1 the first number + * @param num2 the second number + * @return the greatest common divisor of {@code num1} and {@code num2} + */ public static BigInteger gcd(BigInteger num1, BigInteger num2){ while(!num1.equals(BigInteger.ZERO) && !num2.equals(BigInteger.ZERO)){ if(num1.compareTo(num2) > 0){ @@ -517,11 +703,23 @@ public class NumberAlgorithms{ return num1.or(num2); } - //Converts a number to its binary equivalent + //?Converts a number to its binary equivalent + /** + * Converts a number to its binary equivalent. + * + * @param num the number to convert + * @return the binary equivalent of {@code num} + */ public static String toBin(long num){ //Convert the number to binary string return Long.toBinaryString(num); } + /** + * Converts a number to its binary equivalent. + * + * @param num the number to convert + * @return the binary equivalent of {@code num} + */ public static String toBin(BigInteger num){ //Conver the number to binary string return num.toString(2); diff --git a/src/main/java/com/mattrixwv/Stopwatch.java b/src/main/java/com/mattrixwv/Stopwatch.java index 1537737..26539b5 100644 --- a/src/main/java/com/mattrixwv/Stopwatch.java +++ b/src/main/java/com/mattrixwv/Stopwatch.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/Stopwatch.java //Matthew Ellison (Mattrixwv) // Created: 03-01-19 -//Modified: 04-13-23 +//Modified: 08-11-24 //This file contains a class that is used to time the execution time of other programs /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -25,16 +25,49 @@ package com.mattrixwv; import com.mattrixwv.exceptions.InvalidResult; +/** + * A simple stopwatch class to measure elapsed time in various units of resolution. + * + *

+ * This class provides methods to start, stop, and reset a stopwatch, as well as retrieve the + * elapsed time in nanoseconds, microseconds, milliseconds, seconds, minutes, and hours. It + * also includes functionality to get the elapsed time as a formatted string in the most + * appropriate time unit. + *

+ */ public class Stopwatch{ + /** + * The start time of the stopwatch in nanoseconds. + */ private Long startTime; + /** + * The stop time of the stopwatch in nanoseconds. + */ private Long stopTime; - //Constructor makes sure all values are set to defaults + + + //?Constructor makes sure all values are set to defaults + /** + * Constructs a new Stopwatch and initializes the start and stop times to {@code null}. + * This ensures that incorrect function calling order can be detected easily. + */ public Stopwatch(){ //Make sure both values are null so it is easier to detect incorrect function calling order startTime = null; stopTime = null; } - //Returns a long with the elapsed time in nanoseconds. Used by other functions to get the time before converting it to the correct resolution + + + //?Returns a long with the elapsed time in nanoseconds. Used by other functions to get the time before converting it to the correct resolution + /** + * Returns the elapsed time in nanoseconds. + *

+ * If the stopwatch has not been started, it returns {@code 0L}. If the stopwatch has + * been started but not stopped, it returns the time elapsed since it was started. + *

+ * + * @return the elapsed time in nanoseconds + */ private Long getTime(){ if(startTime == null){ return 0L; @@ -46,16 +79,37 @@ public class Stopwatch{ return stopTime - startTime; } } - //An enum that helps keep track of how many times the time has been reduced in the getStr function + + + //?An enum that helps keep track of how many times the time has been reduced in the getStr function + /** + * Enum to represent the time resolution for formatting the time string. + */ private enum TIME_RESOLUTION{ NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, ERROR } - //Simulates starting a stopwatch by saving the time + + + //?Simulates starting a stopwatch by saving the time + /** + * Starts the stopwatch by recording the current time in nanoseconds. + *

+ * If the stopwatch was already running, the previous start time is overwritten. + *

+ */ public void start(){ //Make sure the stop time is reset to 0 stopTime = null; //Get the time as close to returning from the function as possible startTime = System.nanoTime(); } - //Simulates stopping a stopwatch by saving the time + + + //?Simulates stopping a stopwatch by saving the time + /** + * Stops the stopwatch by recording the current time in nanoseconds. + *

+ * If the stopwatch has not been started, this method has no effect. + *

+ */ public void stop(){ //Set the stopTime as close to call time as possible stopTime = System.nanoTime(); @@ -64,42 +118,114 @@ public class Stopwatch{ stopTime = null; } } - //Resets all variables in the stopwatch + + + //?Resets all variables in the stopwatch + /** + * Resets the stopwatch, clearing the start and stop times. + *

+ * After calling this method, the stopwatch needs to be started again before measuring + * elapsed time. + *

+ */ public void reset(){ //Make sure all variables are reset correctly startTime = null; stopTime = null; } - //Returns the time in nanoseconds + + + //?Returns the time in nanoseconds + /** + * Returns the elapsed time in nanoseconds. + * + * @return the elapsed time in nanoseconds as a {@code double} + */ public double getNano(){ return getTime().doubleValue(); } - //Returns the time in microseconds + + + //?Returns the time in microseconds + /** + * Returns the elapsed time in microseconds. + * + * @return the elapsed time in microseconds as a {@code double} + */ public double getMicro(){ return getTime().doubleValue() / 1000D; } - //Returns the time in milliseconds + + + //?Returns the time in milliseconds + /** + * Returns the elapsed time in milliseconds. + * + * @return the elapsed time in milliseconds as a {@code double} + */ public double getMilli(){ return getTime().doubleValue() / 1000000D; } - //Returns the time in seconds + + + //?Returns the time in seconds + /** + * Returns the elapsed time in seconds. + * + * @return the elapsed time in seconds as a {@code double} + */ public double getSecond(){ return getTime().doubleValue() / 1000000000D; } - //Returns the time in minutes + + + //?Returns the time in minutes + /** + * Returns the elapsed time in minutes. + * + * @return the elapsed time in minutes as a {@code double} + */ public double getMinute(){ return getTime().doubleValue() / 60000000000D; } - //Returns the time in hours + + + //?Returns the time in hours + /** + * Returns the elapsed time in hours. + * + * @return the elapsed time in hours as a {@code double} + */ public double getHour(){ return getTime().doubleValue() / 3600000000000D; } - //Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx) + + + //?Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx) + /** + * Returns the elapsed time as a formatted string with the most appropriate resolution. + *

+ * The method automatically selects the best time resolution to display the time in a + * human-readable format. + *

+ * + * @return a formatted string representing the elapsed time + * @throws InvalidResult if the time resolution is invalid + */ public String getStr() throws InvalidResult{ //Get the current duration from time return getStr(getTime().doubleValue()); } + + /** + * Returns a formatted string representing the given time in nanoseconds with the most + * appropriate resolution. + * + * @param nanoseconds the time in nanoseconds to format + * @return a formatted string representing the given time + * @throws InvalidResult if the time resolution is invalid + */ public static String getStr(double nanoseconds) throws InvalidResult{ Double duration = nanoseconds; //Reduce the number to the appropriate number of digits. (xxx.x). @@ -145,6 +271,12 @@ public class Stopwatch{ return time; } + + /** + * Returns a string representation of the elapsed time in the most appropriate resolution. + * + * @return a string representation of the elapsed time + */ @Override public String toString(){ return getStr(); diff --git a/src/main/java/com/mattrixwv/StringAlgorithms.java b/src/main/java/com/mattrixwv/StringAlgorithms.java index 89cff8c..2bec82c 100644 --- a/src/main/java/com/mattrixwv/StringAlgorithms.java +++ b/src/main/java/com/mattrixwv/StringAlgorithms.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java //Matthew Ellison // Created: 07-03-21 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class contains algorithms for strings that I've found it useful to keep around /* - Copyright (C) 2023 Matthew Ellison + Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -27,12 +27,38 @@ import java.util.Collections; import java.util.List; +/** + * Utility class providing algorithms for manipulating and analyzing strings. + * + *

+ * This class offers methods to generate permutations of a string, count occurrences of a character, + * check if a string is a palindrome, and determine if a string is pandigital. + *

+ */ public class StringAlgorithms{ + /** + * Private constructor to prevent instantiation of this utility class. + */ private StringAlgorithms(){} - //This is a function that creates all permutations of a string and returns a vector of those permutations. + + + //?This is a function that creates all permutations of a string and returns a vector of those permutations. + /** + * Generates all permutations of the given string. + * + * @param master the input string for which permutations are to be generated + * @return a list of all permutations of the input string + */ public static List getPermutations(String master){ return getPermutations(master, 0); } + /** + * Generates permutations of the given string starting from the specified index. + * + * @param master the input string for which permutations are to be generated + * @param num the starting index for generating permutations + * @return a list of permutations generated from the specified starting index + */ protected static ArrayList getPermutations(String master, int num){ ArrayList perms = new ArrayList<>(); //Check if the number is out of bounds @@ -65,6 +91,15 @@ public class StringAlgorithms{ //Return the arraylist that was built return perms; } + + /** + * Swaps two characters in the given string. + * + * @param str the string in which the characters are to be swapped + * @param first the index of the first character to be swapped + * @param second the index of the second character to be swapped + * @return a new string with the specified characters swapped + */ private static String swapString(String str, int first, int second){ char[] tempStr = str.toCharArray(); char temp = tempStr[first]; @@ -73,16 +108,43 @@ public class StringAlgorithms{ return new String(tempStr); } - //This function returns the number of times the character occurs in the string + + + //?This function returns the number of times the character occurs in the string + /** + * Counts the number of occurrences of a character in a string. + * + * @param str the string in which to count occurrences + * @param c the character whose occurrences are to be counted + * @return the number of times the character occurs in the string + */ public static long findNumOccurrence(String str, char c){ return str.chars().filter(ch -> ch == c).count(); } - //Returns true if the string passed in is a palindrome + + + //?Returns true if the string passed in is a palindrome + /** + * Checks if a string is a palindrome. + * + * @param str the string to be checked + * @return {@code true} if the string is a palindrome, {@code false} otherwise + */ public static boolean isPalindrome(String str){ String rev = new StringBuilder(str).reverse().toString(); return str.equals(rev); } - //Returns true if the string passed to it is a pandigital + + + //?Returns true if the string passed to it is a pandigital + /** + * Checks if a string is pandigital within a given range of characters. + * + * @param str the string to be checked + * @param bottom the starting character of the pandigital range + * @param top the ending character of the pandigital range + * @return {@code true} if the string is pandigital within the given range, {@code false} otherwise + */ public static boolean isPandigital(String str, char bottom, char top){ //Return false if top < bottom if(top < bottom){ @@ -104,6 +166,12 @@ public class StringAlgorithms{ //If the function has reached this part it has passed all of the falsifying tests return true; } + /** + * Checks if a string is pandigital with respect to the digits 1 through 9. + * + * @param str the string to be checked + * @return {@code true} if the string is pandigital from '1' to '9', {@code false} otherwise + */ public static boolean isPandigital(String str){ return isPandigital(str, '1', '9'); } diff --git a/src/main/java/com/mattrixwv/Triple.java b/src/main/java/com/mattrixwv/Triple.java index 2958e4b..d2aacdb 100644 --- a/src/main/java/com/mattrixwv/Triple.java +++ b/src/main/java/com/mattrixwv/Triple.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/com/mattrixwv/Triple.java //Mattrixwv // Created: 08-20-22 -//Modified: 08-20-22 +//Modified: 08-11-24 //This class implements a triplet of variables /* -Copyright (C) 2022 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -22,27 +22,80 @@ Copyright (C) 2022 Matthew Ellison package com.mattrixwv; +/** + * A generic class representing a set of three elements. + * + *

+ * This class holds three values of potentially different types and provides methods to access them. + *

+ * + * @param the type of the first element + * @param the type of the second element + * @param the type of the third element + */ public class Triple{ + /** + * The first element of the triple + */ private T a; + /** + * The second element of the triple + */ private U b; + /** + * The third element of the triple + */ private V c; + /** + * Constructs a new Triple with the specified values. + * + * @param a the first element of the triple + * @param b the second element of the triple + * @param c the third element of the triple + */ public Triple(T a, U b, V c){ this.a = a; this.b = b; this.c = c; } + /** + * Returns the first element of the triple. + * + * @return the first element of the triple + */ public T getA(){ return a; } + /** + * Returns the second element of the triple. + * + * @return the second element of the triple + */ public U getB(){ return b; } + /** + * Returns the third element of the triple. + * + * @return the third element of the triple + */ public V getC(){ return c; } + /** + * Compares the specified object with this Triple for equality. + * + *

+ * Returns {@code true} if and only if the specified object is also a Triple, and all + * corresponding pairs of elements in the two Triples are equal. + *

+ * + * @param o the object to be compared for equality with this Triple + * @return {@code true} if the specified object is equal to this Triple, {@code false} otherwise + */ @Override public boolean equals(Object o){ if(this == o){ @@ -55,10 +108,27 @@ public class Triple{ return false; } } + + /** + * Returns the hash code value for this Triple. + * + * @return the hash code value for this Triple + */ @Override public int hashCode(){ return a.hashCode() + b.hashCode() * c.hashCode(); } + + /** + * Returns a string representation of the Triple. + * + *

+ * The string representation consists of the string representations of the three elements, + * separated by commas and enclosed in square brackets. + *

+ * + * @return a string representation of the Triple + */ @Override public String toString(){ return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]"; diff --git a/src/main/java/com/mattrixwv/exceptions/InvalidResult.java b/src/main/java/com/mattrixwv/exceptions/InvalidResult.java index a7ee316..1c64664 100644 --- a/src/main/java/com/mattrixwv/exceptions/InvalidResult.java +++ b/src/main/java/com/mattrixwv/exceptions/InvalidResult.java @@ -1,23 +1,59 @@ //JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java //Matthew Ellison // Created: 08-24-20 -//Modified: 04-13-23 +//Modified: 08-11-24 //This is an exception for an invalid result out of one of my algorithms package com.mattrixwv.exceptions; +/** + * The {@code InvalidResult} class extends {@code RuntimeException} and is used to indicate + * that an invalid result has occurred. It provides several constructors to create exceptions + * with a custom message and/or cause. + * + *

This class is a runtime exception, meaning it is unchecked and does not need to be declared + * in a method or constructor's {@code throws} clause.

+ * + * @see RuntimeException + */ public class InvalidResult extends RuntimeException{ - private static final long serialVersionUID = 1L; - + /** + * Constructs a new runtime exception with {@code null} as its detail message. + * The cause is not initialized and may subsequently be initialized by a call to {@link #initCause}. + */ public InvalidResult(){ super(); } + /** + * Constructs a new runtime exception with the specified detail message. The cause is not initialized, + * and may subsequently be initialized by a call to {@link #initCause}. + * + * @param msg the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method. + */ public InvalidResult(String msg){ super(msg); } + /** + * Constructs a new runtime exception with the specified cause and a detail message of + * {@code (cause == null ? null : cause.toString())} (which typically contains the class + * and detail message of {@code cause}). + * + * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). + * A {@code null} value is permitted and indicates that the cause is nonexistent or unknown. + */ public InvalidResult(Throwable cause){ super(cause); } + /** + * Constructs a new runtime exception with the specified detail message and cause. + * + *

Note that the detail message associated with {@code cause} is not automatically incorporated + * in this runtime exception's detail message.

+ * + * @param msg the detail message (which is saved for later retrieval by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). + * A {@code null} value is permitted and indicates that the cause is nonexistent or unknown. + */ public InvalidResult(String msg, Throwable cause){ super(msg, cause); } diff --git a/src/main/java/com/mattrixwv/generators/HexagonalNumberGenerator.java b/src/main/java/com/mattrixwv/generators/HexagonalNumberGenerator.java index 56bcb22..84a6895 100644 --- a/src/main/java/com/mattrixwv/generators/HexagonalNumberGenerator.java +++ b/src/main/java/com/mattrixwv/generators/HexagonalNumberGenerator.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java //Matthew Ellison // Created: 08-20-22 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class generates hexagonal numbers /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -26,18 +26,48 @@ import java.util.Iterator; import java.util.NoSuchElementException; +/** + * A generator for hexagonal numbers, which implements the {@link Iterator} interface. + * + *

+ * Hexagonal numbers are figurate numbers that represent hexagons. The n-th hexagonal number is given by + * the formula: H(n) = 2n^2 - n. + *

+ * + *

+ * This generator allows iteration over hexagonal numbers starting from the first. + *

+ */ public class HexagonalNumberGenerator implements Iterator{ + /** + * The number to generate the next hexagonal number from. + */ protected long num; + + /** + * Constructs a new HexagonalNumberGenerator starting from the first hexagonal number. + */ public HexagonalNumberGenerator(){ num = 1L; } + /** + * Checks if there is a next hexagonal number that can be generated without overflow. + * + * @return {@code true} if the next hexagonal number can be generated, {@code false} otherwise + */ @Override public boolean hasNext(){ return (2 * num * num) > num; } + /** + * Returns the next hexagonal number. + * + * @return the next hexagonal number + * @throws NoSuchElementException if the next hexagonal number would cause overflow + */ @Override public Long next(){ //If the number will result in an overflow throw an exception @@ -52,6 +82,12 @@ public class HexagonalNumberGenerator implements Iterator{ return hexNum; } + /** + * Checks if a given number is a hexagonal number. + * + * @param x the number to check + * @return {@code true} if the number is hexagonal, {@code false} otherwise + */ public static boolean isHexagonal(Long x){ Long n = Math.round((Math.sqrt(1.0D + (8L * x)) + 1L) / 4L); return ((2L * n * n) - n) == x; diff --git a/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java b/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java index 0c88f95..09487c4 100644 --- a/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java +++ b/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java //Mattrixwv // Created: 08-20-22 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class generates pentagonal numbers /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -26,18 +26,47 @@ import java.util.Iterator; import java.util.NoSuchElementException; +/** + * A generator for pentagonal numbers, which implements the {@link Iterator} interface. + * + *

+ * Pentagonal numbers are figurate numbers that represent pentagons. The n-th pentagonal number is given by + * the formula: P(n) = (3n^2 - n) / 2. + *

+ * + *

+ * This generator allows iteration over pentagonal numbers starting from the first. + *

+ */ public class PentagonalNumberGenerator implements Iterator{ + /** + * The number to generate the next pentagonal number from. + */ protected long num; + /** + * Constructs a new PentagonalNumberGenerator starting from the first pentagonal number. + */ public PentagonalNumberGenerator(){ num = 1L; } + /** + * Checks if there is a next pentagonal number that can be generated without overflow. + * + * @return {@code true} if the next pentagonal number can be generated, {@code false} otherwise + */ @Override public boolean hasNext(){ return (3L * num * num) > num; } + /** + * Returns the next pentagonal number. + * + * @return the next pentagonal number + * @throws NoSuchElementException if the next pentagonal number would cause overflow + */ @Override public Long next(){ if(!hasNext()){ @@ -49,6 +78,12 @@ public class PentagonalNumberGenerator implements Iterator{ return pentNum; } + /** + * Checks if a given number is a pentagonal number. + * + * @param x the number to check + * @return {@code true} if the number is pentagonal, {@code false} otherwise + */ public static boolean isPentagonal(Long x){ Long n = Math.round((Math.sqrt(1.0D + (24L * x)) + 1L) / 6L); return (((3L * n * n) - n) / 2L) == x; diff --git a/src/main/java/com/mattrixwv/generators/SieveOfEratosthenes.java b/src/main/java/com/mattrixwv/generators/SieveOfEratosthenes.java index ccbdb05..00f501c 100644 --- a/src/main/java/com/mattrixwv/generators/SieveOfEratosthenes.java +++ b/src/main/java/com/mattrixwv/generators/SieveOfEratosthenes.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java //Matthew Ellison // Created: 06-30-21 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class uses to Sieve of Eratosthenes to generate an infinite number of primes /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -30,21 +30,62 @@ import java.util.Map; import java.util.NoSuchElementException; +/** + * A generator for prime numbers using the Sieve of Eratosthenes algorithm, which implements the {@link Iterator} interface. + * + *

+ * This implementation generates prime numbers in an incremental fashion using a modified version of the Sieve of Eratosthenes algorithm. + * The algorithm uses a map to keep track of the multiples of found prime numbers to efficiently determine the next prime. + *

+ */ public class SieveOfEratosthenes implements Iterator{ + /** + * The next possible prime to be found + */ protected long possiblePrime; + /** + * A dictionary of the primes that have been found and their next multiple + */ protected Map> dict; + /** + * Constructs a new SieveOfEratosthenes instance with an empty prime dictionary + * and starts the search from the first possible prime number, 2. + */ public SieveOfEratosthenes(){ dict = new HashMap<>(); possiblePrime = 2; } + /** + * Indicates whether there is a next prime number available. + * + *

+ * This method always returns {@code true} as the iterator is designed to + * generate primes indefinitely. + *

+ * + * @return {@code true}, as the iterator can generate an infinite number of primes + */ @Override public boolean hasNext(){ return true; } + /** + * Returns the next prime number. + * + *

+ * The method generates the next prime number by checking and updating the + * internal map of known multiples. The first prime returned is 2, and subsequent + * primes are found by incrementing the possible prime number and checking its + * primality using the map. + *

+ * + * @return the next prime number + * @throws NoSuchElementException if the next prime cannot be represented by a {@code long} + */ @Override public Long next(){ long prime; diff --git a/src/main/java/com/mattrixwv/generators/SieveOfEratosthenesBig.java b/src/main/java/com/mattrixwv/generators/SieveOfEratosthenesBig.java index 0aa9760..fb48c2f 100644 --- a/src/main/java/com/mattrixwv/generators/SieveOfEratosthenesBig.java +++ b/src/main/java/com/mattrixwv/generators/SieveOfEratosthenesBig.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java //Matthew Ellison // Created: 06-30-21 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class uses to Sieve of Eratosthenes to generate an infinite number of primes /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -28,23 +28,65 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.NoSuchElementException; +/** + * A generator for prime numbers using the Sieve of Eratosthenes algorithm, which implements the {@link Iterator} interface. + * + *

+ * This implementation generates prime numbers in an incremental fashion using a modified version of the Sieve of Eratosthenes algorithm. + * The algorithm uses a map to keep track of the multiples of found prime numbers to efficiently determine the next prime. + *

+ */ public class SieveOfEratosthenesBig implements Iterator{ + /** + * The next possible prime to be found + */ protected BigInteger possiblePrime; + /** + * A dictionary of the primes that have been found and their next multiple + */ protected Map> dict; + /** + * Constructs a new SieveOfEratosthenes instance with an empty prime dictionary + * and starts the search from the first possible prime number, 2. + */ public SieveOfEratosthenesBig(){ dict = new HashMap<>(); possiblePrime = BigInteger.TWO; } + /** + * Indicates whether there is a next prime number available. + * + *

+ * This method always returns {@code true} as the iterator is designed to + * generate primes indefinitely. + *

+ * + * @return {@code true}, as the iterator can generate an infinite number of primes + */ @Override public boolean hasNext(){ return true; } + /** + * Returns the next prime number. + * + *

+ * The method generates the next prime number by checking and updating the + * internal map of known multiples. The first prime returned is 2, and subsequent + * primes are found by incrementing the possible prime number and checking its + * primality using the map. + *

+ * + * @return the next prime number + * @throws NoSuchElementException if the next prime cannot be represented by a {@code long} + */ @Override public BigInteger next(){ BigInteger prime; @@ -72,6 +114,10 @@ public class SieveOfEratosthenesBig implements Iterator{ //Delete the current entry dict.remove(possiblePrime); } + //Protect against overflows + if(possiblePrime.compareTo(BigInteger.ZERO) < 0){ + throw new NoSuchElementException("the next prime cannot be described by a long"); + } //Save that the number is a prime prime = possiblePrime; //Add the next entry to the prime dictionary diff --git a/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java b/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java index e567e3a..38a0e76 100644 --- a/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java +++ b/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java @@ -1,10 +1,10 @@ //JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java //Mattrixwv // Created: 08-20-22 -//Modified: 04-13-23 +//Modified: 08-11-24 //This class generates triangular numbers /* -Copyright (C) 2023 Matthew Ellison +Copyright (C) 2024 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -26,19 +26,48 @@ import java.util.Iterator; import java.util.NoSuchElementException; +/** + * A generator for triangular numbers, which implements the {@link Iterator} interface. + * + *

+ * Triangular numbers are figurate numbers that represent triangles. The n-th triangular number is given by + * the formula: T(n) = n(n + 1) / 2. + *

+ * + *

+ * This generator allows iteration over triangular numbers starting from the first. + *

+ */ public class TriangularNumberGenerator implements Iterator{ + /** + * The number to generate the next triangular number from + */ protected long num; + /** + * Constructs a new TriangularNumberGenerator starting from the first triangular number. + */ public TriangularNumberGenerator(){ num = 1L; } + /** + * Checks if there is a next triangular number that can be generated without overflow. + * + * @return {@code true} if the next triangular number can be generated, {@code false} otherwise + */ @Override public boolean hasNext(){ return ((num * num) + num) > num; } + /** + * Returns the next triangular number. + * + * @return the next triangular number + * @throws NoSuchElementException if the next triangular number would cause overflow + */ @Override public Long next(){ if(!hasNext()){ @@ -50,6 +79,12 @@ public class TriangularNumberGenerator implements Iterator{ return newNum; } + /** + * Checks if a given number is a triangular number. + * + * @param x the number to check + * @return {@code true} if the number is triangular, {@code false} otherwise + */ public static boolean isTriangular(Long x){ Long n = Math.round((Math.sqrt(1.0D + (8L * x)) - 1L) / 2L); return (((n * n) + n) / 2L) == x;