19 Commits

Author SHA1 Message Date
46a6c01be8 Fix deployment issue 2026-01-26 18:30:28 -05:00
25a70331f5 Update version and URLs 2026-01-26 18:25:34 -05:00
d5fb7b4521 Fix sonarqube issues 2026-01-26 18:20:59 -05:00
abf61f5395 Add badge to README 2026-01-26 18:18:09 -05:00
2dfd645577 Update deployment issues 2026-01-26 18:18:01 -05:00
284cd73b24 Update dependencies 2026-01-26 10:17:21 -05:00
2828fd4f58 Update to make maven 4 compliant 2026-01-26 10:15:58 -05:00
8877fc7193 Updated snapshot version 2025-12-21 12:12:38 -05:00
ba6d836c88 Update dependencies 2025-12-21 12:08:01 -05:00
81fc3fdf95 Update snapshot version 2025-05-24 12:31:48 -04:00
4522a0c3de Update dependencies and plugins 2025-05-24 12:29:15 -04:00
5ed14545e7 Update snapshot version 2025-01-11 12:05:16 -05:00
2d76848a69 Update dependencies and plugins 2025-01-11 11:59:01 -05:00
7e66910d8c Update with nvd api key 2024-08-16 23:31:19 -04:00
00658869d2 Update snapshot version 2024-08-11 21:41:17 -04:00
efdc72a71e Fix version number 2024-08-11 21:38:06 -04:00
dbac819ac9 Fix broken javadoc comments 2024-08-11 21:37:35 -04:00
3feefdb7dd Added javadoc comments 2024-08-11 21:31:00 -04:00
ae1346dbcd Update snapshot version 2024-08-08 22:10:15 -04:00
14 changed files with 1030 additions and 234 deletions

View File

@@ -1,23 +1,15 @@
# JavaClasses # JavaClasses
[![Quality Gate Status](https://sonarqube.mattrixwv.com/api/project_badges/measure?project=JavaClasses&metric=alert_status&token=sqb_393560530c97c2e9f2bc1df1b34c801926363baa)](https://sonarqube.mattrixwv.com/dashboard?id=JavaClasses)
This is a set of classes and functions, not part of the standard library, that I have found it helpful to keep around. This is a set of classes and functions, not part of the standard library, that I have found it helpful to keep around.
# Installation ## Stopwatch
In order to use these in a program they need to be installed with maven. I normally use `mvn clean package install`. From there you can import them into a maven project using
```XML
<dependency>
<groupId>mattrixwv</groupId>
<artifactId>myClasses</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
```
Then import them into a program by `import mattrixwv.Algorithms;` or `import mattrixwv.Stopwatch;`.
# Stopwatch
This is a class that allows you to determine the execution time of an algorithm. This is a class that allows you to determine the execution time of an algorithm.
You can get specific resolutions of time through their own get functions, all of which return double. You can get specific resolutions of time through their own get functions, all of which return double.
However I have built it a function, getStr(), that automatically chooses the best resolution and returns both the number and resolution as a string. However I have built it a function, getStr(), that automatically chooses the best resolution and returns both the number and resolution as a string.
Example of usage:
```Java ```Java
Stopwatch timer = new Stopwatch(); Stopwatch timer = new Stopwatch();
timer.start(); timer.start();
@@ -28,6 +20,7 @@ Example of usage:
System.out.printf("It took %f milliseconds to run this algorithm", timer.getMilli()); System.out.printf("It took %f milliseconds to run this algorithm", timer.getMilli());
``` ```
# Algorithms ## Algorithms
This is a class that contains many different algorithms that I have found it useful to keep around. This is used extensively in my ProjectEuler code found at https://bitbucket.org/Mattrixwv/ProjectEuler
This is a class that contains many different algorithms that I have found it useful to keep around. This is used extensively in my [Project Euler](https://git.mattrixwv.com/ProjectEuler/ProjectEulerJava) project.
All methods are overloaded to allow for using Integer, Long, and BigInteger types. All methods are overloaded to allow for using Integer, Long, and BigInteger types.

180
pom.xml
View File

@@ -20,58 +20,125 @@
</developers> </developers>
<scm> <scm>
<connection>scm:git:git://bitbucket.org/Mattrixwv/Matrix.git</connection> <connection>scm:git:git://git.mattrixwv.com/BaseLibraries/JavaClasses.git</connection>
<developerConnection>scm:git:ssh://bitbucket.org:Mattrixwv/Matrix.git</developerConnection> <developerConnection>scm:git:ssh://git.mattrixwv.com/BaseLibraries/JavaClasses.git</developerConnection>
<url>https://bitbucket.org/Mattrixwv/Matrix/src</url> <url>https://git.mattrixwv.com/BaseLibraries/JavaClasses</url>
</scm> </scm>
<groupId>com.mattrixwv</groupId> <groupId>com.mattrixwv</groupId>
<artifactId>myClasses</artifactId> <artifactId>myClasses</artifactId>
<version>1.3.5</version> <version>1.4.1</version>
<name>myClasses</name> <name>myClasses</name>
<description>A grouping of functions that I've found useful</description> <description>A grouping of functions that I've found useful</description>
<url>www.mattrixwv.com</url> <url>www.mattrixwv.com</url>
<properties> <properties>
<!--Compile--> <!--Compile-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>21</maven.compiler.source> <java.version>25</java.version>
<maven.compiler.target>21</maven.compiler.target> <maven.compiler.source>25</maven.compiler.source>
<java.version>21</java.version> <maven.compiler.target>25</maven.compiler.target>
<!--Sonarqube--> <!--Sonarqube-->
<sonar.java.source>21</sonar.java.source> <sonar.java.source>25</sonar.java.source>
<sonar.dependencyCheck.jsonReportPath>target/dependency-check-report.json</sonar.dependencyCheck.jsonReportPath> <sonar.dependencyCheck.jsonReportPath>target/dependency-check-report.json</sonar.dependencyCheck.jsonReportPath>
<sonar.dependencyCheck.htmlReportPath>target/dependency-check-report.html</sonar.dependencyCheck.htmlReportPath> <sonar.dependencyCheck.htmlReportPath>target/dependency-check-report.html</sonar.dependencyCheck.htmlReportPath>
<!--Deployment-->
<gpg.keyname>3BA6515C8FF145249BEBBEABA52FDEC4259179D4</gpg.keyname>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit-jupiter</artifactId>
<version>5.10.3</version> <version>6.0.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<!--Ensure maven is the correct version-->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId> <artifactId>maven-enforcer-plugin</artifactId>
<version>3.5.0</version>
<executions> <executions>
<execution> <execution>
<id>enforce-maven</id> <id>enforce-maven</id>
<goals> <goals>
<goal>enforce</goal> <goal>enforce</goal>
</goals> </goals>
</execution>
</executions>
</plugin>
<!--Sonarqube-->
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<executions>
<execution>
<id>dependency-check</id>
<phase>verify</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<!--Deployment-->
<plugin>
<groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--Ensure maven is the correct version-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.6.2</version>
<configuration> <configuration>
<rules> <rules>
<requireMavenVersion> <requireMavenVersion>
@@ -79,20 +146,21 @@
</requireMavenVersion> </requireMavenVersion>
</rules> </rules>
</configuration> </configuration>
</execution>
</executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.5.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.4.0</version> <version>3.4.0</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-resources-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId>
<version>3.3.1</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version> <version>3.14.1</version>
<configuration> <configuration>
<release>${java.version}</release> <release>${java.version}</release>
<compilerArgs> <compilerArgs>
@@ -103,33 +171,34 @@
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.3.1</version> <version>3.5.4</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version> <version>3.5.0</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId> <artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version> <version>3.1.4</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId> <artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version> <version>3.21.0</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId> <artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.2</version> <version>3.9.0</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId> <artifactId>versions-maven-plugin</artifactId>
<version>2.17.1</version> <version>2.21.0</version>
<configuration> <configuration>
<rulesUri>file://${session.executionRootDirectory}/version-rules.xml</rulesUri> <rulesUri>file://${session.executionRootDirectory}/version-rules.xml</rulesUri>
</configuration> </configuration>
@@ -137,19 +206,19 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version> <version>3.9.0</version>
</plugin> </plugin>
<!--Sonarqube--> <!--Sonarqube-->
<plugin> <plugin>
<groupId>org.sonarsource.scanner.maven</groupId> <groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId> <artifactId>sonar-maven-plugin</artifactId>
<version>4.0.0.4121</version> <version>5.5.0.6356</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.12</version> <version>0.8.14</version>
<executions> <executions>
<execution> <execution>
<id>jacoco-initialize</id> <id>jacoco-initialize</id>
@@ -170,7 +239,7 @@
<plugin> <plugin>
<groupId>org.owasp</groupId> <groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId> <artifactId>dependency-check-maven</artifactId>
<version>10.0.3</version> <version>12.2.0</version>
<executions> <executions>
<execution> <execution>
<phase>none</phase> <phase>none</phase>
@@ -184,6 +253,9 @@
<format>json</format> <format>json</format>
<format>html</format> <format>html</format>
</formats> </formats>
<nvdApiServerId>nvd</nvdApiServerId>
<failBuildOnCVSS>7</failBuildOnCVSS>
<ossIndexServerId>ossindex</ossIndexServerId>
</configuration> </configuration>
</plugin> </plugin>
@@ -191,29 +263,27 @@
<plugin> <plugin>
<groupId>org.sonatype.central</groupId> <groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId> <artifactId>central-publishing-maven-plugin</artifactId>
<version>0.5.0</version> <version>0.10.0</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<publishingServerId>ossrh</publishingServerId> <publishingServerId>central</publishingServerId>
<autoPublish>true</autoPublish>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>1.7.0</version> <version>3.1.4</version>
<extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <skip>true</skip>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterCloase>true</autoReleaseAfterCloase>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>3.3.1</version> <version>3.4.0</version>
<executions> <executions>
<execution> <execution>
<id>attach-sources</id> <id>attach-sources</id>
@@ -227,7 +297,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.8.0</version> <version>3.12.0</version>
<executions> <executions>
<execution> <execution>
<id>attach-javadocs</id> <id>attach-javadocs</id>
@@ -241,21 +311,9 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>3.2.4</version> <version>3.2.8</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<keyname>${gpg.keyname}</keyname>
<passphraseServerId>${gpg.keyname}</passphraseServerId>
</configuration>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement>
</build> </build>
</project> </project>

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java //JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java
//Matthew Ellison //Matthew Ellison
// Created: 07-03-21 // 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 //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 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 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; 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.
*
* <p>This class is not intended to be instantiated.</p>
*/
public class ArrayAlgorithms{ public class ArrayAlgorithms{
/**
* Private constructor to prevent instantiation of this utility class.
*/
private ArrayAlgorithms(){} 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<Integer> nums){ public static int getSum(Iterable<Integer> nums){
//Setup the variables //Setup the variables
int sum = 0; int sum = 0;
@@ -43,6 +60,12 @@ public class ArrayAlgorithms{
//Return the sum of all elements //Return the sum of all elements
return sum; 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<Long> nums){ public static long getLongSum(Iterable<Long> nums){
//Setup the variables //Setup the variables
long sum = 0; long sum = 0;
@@ -55,6 +78,12 @@ public class ArrayAlgorithms{
//Return the sum of all elements //Return the sum of all elements
return sum; 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<BigInteger> nums){ public static BigInteger getBigSum(Iterable<BigInteger> nums){
//Setup the variables //Setup the variables
BigInteger sum = BigInteger.ZERO; BigInteger sum = BigInteger.ZERO;
@@ -67,7 +96,15 @@ public class ArrayAlgorithms{
//Return the sum of all elements //Return the sum of all elements
return sum; 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<Integer> nums){ public static int getProd(Iterable<Integer> nums){
//If a blank list was passed tot he fuction return 0 as the product //If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){ if(!nums.iterator().hasNext()){
@@ -85,6 +122,13 @@ public class ArrayAlgorithms{
//Return the product of all elements //Return the product of all elements
return product; 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<Long> nums){ public static long getLongProd(Iterable<Long> nums){
//If a blank list was passed tot he fuction return 0 as the product //If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){ if(!nums.iterator().hasNext()){
@@ -102,6 +146,13 @@ public class ArrayAlgorithms{
//Return the product of all elements //Return the product of all elements
return product; 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<BigInteger> nums){ public static BigInteger getBigProd(Iterable<BigInteger> nums){
//If a blank list was passed tot he fuction return 0 as the product //If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){ if(!nums.iterator().hasNext()){
@@ -119,7 +170,16 @@ public class ArrayAlgorithms{
//Return the product of all elements //Return the product of all elements
return product; 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 <T> the type of elements in the collection
* @return a string representation of the collection
*/
public static <T> String printList(Iterable<T> list){ public static <T> String printList(Iterable<T> list){
StringJoiner returnString = new StringJoiner(", ", "[", "]"); StringJoiner returnString = new StringJoiner(", ", "[", "]");
for(T obj : list){ for(T obj : list){
@@ -127,7 +187,14 @@ public class ArrayAlgorithms{
} }
return returnString.toString(); 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<Integer> longToInt(List<Long> originalList){ public static List<Integer> longToInt(List<Long> originalList){
ArrayList<Integer> newList = new ArrayList<>(originalList.size()); ArrayList<Integer> newList = new ArrayList<>(originalList.size());
for(Long num : originalList){ for(Long num : originalList){

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/NumberAlgorithms.java //JavaClasses/src/main/java/mattrixwv/NumberAlgorithms.java
//Matthew Ellison //Matthew Ellison
// Created: 07-03-21 // 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 //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 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 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; 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.
* <p> This class cannot be instantiated. </p>
*/
public class NumberAlgorithms{ public class NumberAlgorithms{
/**
* Private constructor to prevent instantiation
*/
private NumberAlgorithms(){} private NumberAlgorithms(){}
/**
* Error message used for invalid factorial inputs.
*/
public static final String FACTORIAL_NEGATIVE_MESSAGE = "n! cannot be negative"; 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<Integer> getPrimes(int goalNumber){ public static List<Integer> getPrimes(int goalNumber){
return ArrayAlgorithms.longToInt(getPrimes((long) 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<Long> getPrimes(long goalNumber){ public static List<Long> getPrimes(long goalNumber){
ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found 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); 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){ for(long possiblePrime = 3L;possiblePrime <= goalNumber;possiblePrime += 2L){
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime)); Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime));
@@ -79,6 +104,12 @@ public class NumberAlgorithms{
Collections.sort(primes); Collections.sort(primes);
return 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<BigInteger> getPrimes(BigInteger goalNumber){ public static List<BigInteger> getPrimes(BigInteger goalNumber){
ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found 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<Integer> getNumPrimes(int numberOfPrimes){ public static List<Integer> getNumPrimes(int numberOfPrimes){
return ArrayAlgorithms.longToInt(getNumPrimes((long)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<Long> getNumPrimes(long numberOfPrimes){ public static List<Long> getNumPrimes(long numberOfPrimes){
ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found 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); Collections.sort(primes);
return 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<BigInteger> getNumPrimes(BigInteger numberOfPrimes){ public static List<BigInteger> getNumPrimes(BigInteger numberOfPrimes){
ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found 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){ public static boolean isPrime(long possiblePrime){
if(possiblePrime <= 3){ if(possiblePrime <= 3){
return possiblePrime > 1; return possiblePrime > 1;
@@ -216,6 +272,12 @@ public class NumberAlgorithms{
} }
return true; 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){ public static boolean isPrime(BigInteger possiblePrime){
if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){ if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){
return possiblePrime.compareTo(BigInteger.ONE) > 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<Integer> getFactors(int goalNumber) throws InvalidResult{ public static List<Integer> getFactors(int goalNumber) throws InvalidResult{
return ArrayAlgorithms.longToInt(getFactors((long)goalNumber)); 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<Long> getFactors(long goalNumber) throws InvalidResult{ public static List<Long> getFactors(long goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them //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)); Double topPossiblePrime = Math.ceil(Math.sqrt(goalNumber));
@@ -270,6 +345,12 @@ public class NumberAlgorithms{
//Return the list of factors //Return the list of factors
return 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<BigInteger> getFactors(BigInteger goalNumber) throws InvalidResult{ public static List<BigInteger> getFactors(BigInteger goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them //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); 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<Integer> getDivisors(int goalNumber){ public static List<Integer> getDivisors(int goalNumber){
return ArrayAlgorithms.longToInt(getDivisors((long)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<Long> getDivisors(long goalNumber){ public static List<Long> getDivisors(long goalNumber){
HashSet<Long> divisors = new HashSet<>(); HashSet<Long> divisors = new HashSet<>();
//Start by checking that the number is positive //Start by checking that the number is positive
@@ -338,6 +432,12 @@ public class NumberAlgorithms{
//Return the list //Return the list
return divisorList; 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<BigInteger> getDivisors(BigInteger goalNumber){ public static List<BigInteger> getDivisors(BigInteger goalNumber){
HashSet<BigInteger> divisors = new HashSet<>(); HashSet<BigInteger> divisors = new HashSet<>();
//Start by checking that the number is positive //Start by checking that the number is positive
@@ -367,10 +467,24 @@ public class NumberAlgorithms{
return divisorList; 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){ public static int getFib(int goalSubscript){
return (int)getFib((long)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){ public static long getFib(long goalSubscript){
//Setup the variables //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 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 the proper number. The location counter is 1 off of the subscript
return fibNums[(fibLoc - 1) % 3]; 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){ public static BigInteger getFib(BigInteger goalSubscript){
//Setup the variables //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 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]; 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<Integer> getAllFib(int goalNumber){ public static List<Integer> getAllFib(int goalNumber){
return ArrayAlgorithms.longToInt(getAllFib((long) 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<Long> getAllFib(long goalNumber){ public static List<Long> getAllFib(long goalNumber){
//Setup the variables //Setup the variables
ArrayList<Long> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers ArrayList<Long> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
@@ -434,6 +568,12 @@ public class NumberAlgorithms{
fibNums.remove(fibNums.size() - 1); fibNums.remove(fibNums.size() - 1);
return fibNums; 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<BigInteger> getAllFib(BigInteger goalNumber){ public static List<BigInteger> getAllFib(BigInteger goalNumber){
//Setup the variables //Setup the variables
ArrayList<BigInteger> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers ArrayList<BigInteger> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
@@ -457,10 +597,26 @@ public class NumberAlgorithms{
return fibNums; 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 num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
* @see #factorial(long)
*/
public static int factorial(int num) throws InvalidParameterException{ public static int factorial(int num) throws InvalidParameterException{
return (int)factorial((long)num); return (int)factorial((long)num);
} }
/**
* Calculates the factorial of the specified number.
*
* @param num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
*/
public static long factorial(long num) throws InvalidParameterException{ public static long factorial(long num) throws InvalidParameterException{
long fact = 1L; //The value of the factorial long fact = 1L; //The value of the factorial
@@ -475,6 +631,13 @@ public class NumberAlgorithms{
return fact; return fact;
} }
/**
* Calculates the factorial of the specified number.
*
* @param num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
*/
public static BigInteger factorial(BigInteger num) throws InvalidParameterException{ public static BigInteger factorial(BigInteger num) throws InvalidParameterException{
BigInteger fact = BigInteger.valueOf(1L); BigInteger fact = BigInteger.valueOf(1L);
@@ -490,10 +653,26 @@ public class NumberAlgorithms{
return fact; 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){ public static int gcd(int num1, int num2){
return (int)gcd((long)num1, (long)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){ public static long gcd(long num1, long num2){
while((num1 != 0) && (num2 != 0)){ while((num1 != 0) && (num2 != 0)){
if(num1 > num2){ if(num1 > num2){
@@ -505,6 +684,13 @@ public class NumberAlgorithms{
} }
return num1 | num2; 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){ public static BigInteger gcd(BigInteger num1, BigInteger num2){
while(!num1.equals(BigInteger.ZERO) && !num2.equals(BigInteger.ZERO)){ while(!num1.equals(BigInteger.ZERO) && !num2.equals(BigInteger.ZERO)){
if(num1.compareTo(num2) > 0){ if(num1.compareTo(num2) > 0){
@@ -517,11 +703,23 @@ public class NumberAlgorithms{
return num1.or(num2); 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){ public static String toBin(long num){
//Convert the number to binary string //Convert the number to binary string
return Long.toBinaryString(num); 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){ public static String toBin(BigInteger num){
//Conver the number to binary string //Conver the number to binary string
return num.toString(2); return num.toString(2);

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/Stopwatch.java //JavaClasses/src/main/java/mattrixwv/Stopwatch.java
//Matthew Ellison (Mattrixwv) //Matthew Ellison (Mattrixwv)
// Created: 03-01-19 // 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 //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 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 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; import com.mattrixwv.exceptions.InvalidResult;
/**
* A simple stopwatch class to measure elapsed time in various units of resolution.
*
* <p>
* 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.
* </p>
*/
public class Stopwatch{ public class Stopwatch{
/**
* The start time of the stopwatch in nanoseconds.
*/
private Long startTime; private Long startTime;
/**
* The stop time of the stopwatch in nanoseconds.
*/
private Long stopTime; 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(){ public Stopwatch(){
//Make sure both values are null so it is easier to detect incorrect function calling order //Make sure both values are null so it is easier to detect incorrect function calling order
startTime = null; startTime = null;
stopTime = 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.
* <p>
* 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.
* </p>
*
* @return the elapsed time in nanoseconds
*/
private Long getTime(){ private Long getTime(){
if(startTime == null){ if(startTime == null){
return 0L; return 0L;
@@ -46,16 +79,37 @@ public class Stopwatch{
return stopTime - startTime; 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 } 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.
* <p>
* If the stopwatch was already running, the previous start time is overwritten.
* </p>
*/
public void start(){ public void start(){
//Make sure the stop time is reset to 0 //Make sure the stop time is reset to 0
stopTime = null; stopTime = null;
//Get the time as close to returning from the function as possible //Get the time as close to returning from the function as possible
startTime = System.nanoTime(); 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.
* <p>
* If the stopwatch has not been started, this method has no effect.
* </p>
*/
public void stop(){ public void stop(){
//Set the stopTime as close to call time as possible //Set the stopTime as close to call time as possible
stopTime = System.nanoTime(); stopTime = System.nanoTime();
@@ -64,42 +118,114 @@ public class Stopwatch{
stopTime = null; stopTime = null;
} }
} }
//Resets all variables in the stopwatch
//?Resets all variables in the stopwatch
/**
* Resets the stopwatch, clearing the start and stop times.
* <p>
* After calling this method, the stopwatch needs to be started again before measuring
* elapsed time.
* </p>
*/
public void reset(){ public void reset(){
//Make sure all variables are reset correctly //Make sure all variables are reset correctly
startTime = null; startTime = null;
stopTime = 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(){ public double getNano(){
return getTime().doubleValue(); 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(){ public double getMicro(){
return getTime().doubleValue() / 1000D; 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(){ public double getMilli(){
return getTime().doubleValue() / 1000000D; 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(){ public double getSecond(){
return getTime().doubleValue() / 1000000000D; 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(){ public double getMinute(){
return getTime().doubleValue() / 60000000000D; 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(){ public double getHour(){
return getTime().doubleValue() / 3600000000000D; 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.
* <p>
* The method automatically selects the best time resolution to display the time in a
* human-readable format.
* </p>
*
* @return a formatted string representing the elapsed time
* @throws InvalidResult if the time resolution is invalid
*/
public String getStr() throws InvalidResult{ public String getStr() throws InvalidResult{
//Get the current duration from time //Get the current duration from time
return getStr(getTime().doubleValue()); 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{ public static String getStr(double nanoseconds) throws InvalidResult{
Double duration = nanoseconds; Double duration = nanoseconds;
//Reduce the number to the appropriate number of digits. (xxx.x). //Reduce the number to the appropriate number of digits. (xxx.x).
@@ -145,6 +271,12 @@ public class Stopwatch{
return time; return time;
} }
/**
* Returns a string representation of the elapsed time in the most appropriate resolution.
*
* @return a string representation of the elapsed time
*/
@Override @Override
public String toString(){ public String toString(){
return getStr(); return getStr();

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java //JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java
//Matthew Ellison //Matthew Ellison
// Created: 07-03-21 // 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 //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 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 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; import java.util.List;
/**
* Utility class providing algorithms for manipulating and analyzing strings.
*
* <p>
* 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.
* </p>
*/
public class StringAlgorithms{ public class StringAlgorithms{
/**
* Private constructor to prevent instantiation of this utility class.
*/
private StringAlgorithms(){} 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<String> getPermutations(String master){ public static List<String> getPermutations(String master){
return getPermutations(master, 0); 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<String> getPermutations(String master, int num){ protected static ArrayList<String> getPermutations(String master, int num){
ArrayList<String> perms = new ArrayList<>(); ArrayList<String> perms = new ArrayList<>();
//Check if the number is out of bounds //Check if the number is out of bounds
@@ -65,6 +91,15 @@ public class StringAlgorithms{
//Return the arraylist that was built //Return the arraylist that was built
return perms; 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){ private static String swapString(String str, int first, int second){
char[] tempStr = str.toCharArray(); char[] tempStr = str.toCharArray();
char temp = tempStr[first]; char temp = tempStr[first];
@@ -73,16 +108,43 @@ public class StringAlgorithms{
return new String(tempStr); 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){ public static long findNumOccurrence(String str, char c){
return str.chars().filter(ch -> ch == c).count(); 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){ public static boolean isPalindrome(String str){
String rev = new StringBuilder(str).reverse().toString(); String rev = new StringBuilder(str).reverse().toString();
return str.equals(rev); 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){ public static boolean isPandigital(String str, char bottom, char top){
//Return false if top < bottom //Return false if top < bottom
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 //If the function has reached this part it has passed all of the falsifying tests
return true; 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){ public static boolean isPandigital(String str){
return isPandigital(str, '1', '9'); return isPandigital(str, '1', '9');
} }

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/Triple.java //JavaClasses/src/main/java/com/mattrixwv/Triple.java
//Mattrixwv //Mattrixwv
// Created: 08-20-22 // Created: 08-20-22
//Modified: 08-20-22 //Modified: 08-11-24
//This class implements a triplet of variables //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 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 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; package com.mattrixwv;
/**
* A generic class representing a set of three elements.
*
* <p>
* This class holds three values of potentially different types and provides methods to access them.
* </p>
*
* @param <T> the type of the first element
* @param <U> the type of the second element
* @param <V> the type of the third element
*/
public class Triple<T, U, V>{ public class Triple<T, U, V>{
/**
* The first element of the triple
*/
private T a; private T a;
/**
* The second element of the triple
*/
private U b; private U b;
/**
* The third element of the triple
*/
private V c; 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){ public Triple(T a, U b, V c){
this.a = a; this.a = a;
this.b = b; this.b = b;
this.c = c; this.c = c;
} }
/**
* Returns the first element of the triple.
*
* @return the first element of the triple
*/
public T getA(){ public T getA(){
return a; return a;
} }
/**
* Returns the second element of the triple.
*
* @return the second element of the triple
*/
public U getB(){ public U getB(){
return b; return b;
} }
/**
* Returns the third element of the triple.
*
* @return the third element of the triple
*/
public V getC(){ public V getC(){
return c; return c;
} }
/**
* Compares the specified object with this Triple for equality.
*
* <p>
* 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.
* </p>
*
* @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 @Override
public boolean equals(Object o){ public boolean equals(Object o){
if(this == o){ if(this == o){
@@ -55,10 +108,27 @@ public class Triple<T, U, V>{
return false; return false;
} }
} }
/**
* Returns the hash code value for this Triple.
*
* @return the hash code value for this Triple
*/
@Override @Override
public int hashCode(){ public int hashCode(){
return a.hashCode() + b.hashCode() * c.hashCode(); return a.hashCode() + b.hashCode() * c.hashCode();
} }
/**
* Returns a string representation of the Triple.
*
* <p>
* The string representation consists of the string representations of the three elements,
* separated by commas and enclosed in square brackets.
* </p>
*
* @return a string representation of the Triple
*/
@Override @Override
public String toString(){ public String toString(){
return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]"; return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]";

View File

@@ -1,23 +1,59 @@
//JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java
//Matthew Ellison
// Created: 08-24-20
//Modified: 04-13-23
//This is an exception for an invalid result out of one of my algorithms
package com.mattrixwv.exceptions; 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.
*
* <p>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.</p>
*
* @see RuntimeException
*/
public class InvalidResult extends RuntimeException{ public class InvalidResult extends RuntimeException{
private static final long serialVersionUID = 1L; /**
* Serialization identifier for this class
*/
public 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(){ public InvalidResult(){
super(); 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){ public InvalidResult(String msg){
super(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){ public InvalidResult(Throwable cause){
super(cause); super(cause);
} }
/**
* Constructs a new runtime exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is not automatically incorporated
* in this runtime exception's detail message.</p>
*
* @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){ public InvalidResult(String msg, Throwable cause){
super(msg, cause); super(msg, cause);
} }

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java //JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java
//Matthew Ellison //Matthew Ellison
// Created: 08-20-22 // Created: 08-20-22
//Modified: 04-13-23 //Modified: 08-11-24
//This class generates hexagonal numbers //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 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 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; import java.util.NoSuchElementException;
/**
* A generator for hexagonal numbers, which implements the {@link Iterator} interface.
*
* <p>
* Hexagonal numbers are figurate numbers that represent hexagons. The n-th hexagonal number is given by
* the formula: H(n) = 2n^2 - n.
* </p>
*
* <p>
* This generator allows iteration over hexagonal numbers starting from the first.
* </p>
*/
public class HexagonalNumberGenerator implements Iterator<Long>{ public class HexagonalNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next hexagonal number from.
*/
protected long num; protected long num;
/**
* Constructs a new HexagonalNumberGenerator starting from the first hexagonal number.
*/
public HexagonalNumberGenerator(){ public HexagonalNumberGenerator(){
num = 1L; 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 @Override
public boolean hasNext(){ public boolean hasNext(){
return (2 * num * num) > num; 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 @Override
public Long next(){ public Long next(){
//If the number will result in an overflow throw an exception //If the number will result in an overflow throw an exception
@@ -52,6 +82,12 @@ public class HexagonalNumberGenerator implements Iterator<Long>{
return hexNum; 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){ public static boolean isHexagonal(Long x){
Long n = Math.round((Math.sqrt(1.0D + (8L * x)) + 1L) / 4L); Long n = Math.round((Math.sqrt(1.0D + (8L * x)) + 1L) / 4L);
return ((2L * n * n) - n) == x; return ((2L * n * n) - n) == x;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java //JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java
//Mattrixwv //Mattrixwv
// Created: 08-20-22 // Created: 08-20-22
//Modified: 04-13-23 //Modified: 08-11-24
//This class generates pentagonal numbers //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 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 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; import java.util.NoSuchElementException;
/**
* A generator for pentagonal numbers, which implements the {@link Iterator} interface.
*
* <p>
* Pentagonal numbers are figurate numbers that represent pentagons. The n-th pentagonal number is given by
* the formula: P(n) = (3n^2 - n) / 2.
* </p>
*
* <p>
* This generator allows iteration over pentagonal numbers starting from the first.
* </p>
*/
public class PentagonalNumberGenerator implements Iterator<Long>{ public class PentagonalNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next pentagonal number from.
*/
protected long num; protected long num;
/**
* Constructs a new PentagonalNumberGenerator starting from the first pentagonal number.
*/
public PentagonalNumberGenerator(){ public PentagonalNumberGenerator(){
num = 1L; 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 @Override
public boolean hasNext(){ public boolean hasNext(){
return (3L * num * num) > num; 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 @Override
public Long next(){ public Long next(){
if(!hasNext()){ if(!hasNext()){
@@ -49,6 +78,12 @@ public class PentagonalNumberGenerator implements Iterator<Long>{
return pentNum; 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){ public static boolean isPentagonal(Long x){
Long n = Math.round((Math.sqrt(1.0D + (24L * x)) + 1L) / 6L); Long n = Math.round((Math.sqrt(1.0D + (24L * x)) + 1L) / 6L);
return (((3L * n * n) - n) / 2L) == x; return (((3L * n * n) - n) / 2L) == x;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java //JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java
//Matthew Ellison //Matthew Ellison
// Created: 06-30-21 // 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 //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 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 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; import java.util.NoSuchElementException;
/**
* A generator for prime numbers using the Sieve of Eratosthenes algorithm, which implements the {@link Iterator} interface.
*
* <p>
* 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.
* </p>
*/
public class SieveOfEratosthenes implements Iterator<Long>{ public class SieveOfEratosthenes implements Iterator<Long>{
/**
* The next possible prime to be found
*/
protected long possiblePrime; protected long possiblePrime;
/**
* A dictionary of the primes that have been found and their next multiple
*/
protected Map<Long, ArrayList<Long>> dict; protected Map<Long, ArrayList<Long>> dict;
/**
* Constructs a new SieveOfEratosthenes instance with an empty prime dictionary
* and starts the search from the first possible prime number, 2.
*/
public SieveOfEratosthenes(){ public SieveOfEratosthenes(){
dict = new HashMap<>(); dict = new HashMap<>();
possiblePrime = 2; possiblePrime = 2;
} }
/**
* Indicates whether there is a next prime number available.
*
* <p>
* This method always returns {@code true} as the iterator is designed to
* generate primes indefinitely.
* </p>
*
* @return {@code true}, as the iterator can generate an infinite number of primes
*/
@Override @Override
public boolean hasNext(){ public boolean hasNext(){
return true; return true;
} }
/**
* Returns the next prime number.
*
* <p>
* 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.
* </p>
*
* @return the next prime number
* @throws NoSuchElementException if the next prime cannot be represented by a {@code long}
*/
@Override @Override
public Long next(){ public Long next(){
long prime; long prime;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java //JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
//Matthew Ellison //Matthew Ellison
// Created: 06-30-21 // 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 //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 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 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.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; 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.
*
* <p>
* 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.
* </p>
*/
public class SieveOfEratosthenesBig implements Iterator<BigInteger>{ public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
/**
* The next possible prime to be found
*/
protected BigInteger possiblePrime; protected BigInteger possiblePrime;
/**
* A dictionary of the primes that have been found and their next multiple
*/
protected Map<BigInteger, ArrayList<BigInteger>> dict; protected Map<BigInteger, ArrayList<BigInteger>> dict;
/**
* Constructs a new SieveOfEratosthenes instance with an empty prime dictionary
* and starts the search from the first possible prime number, 2.
*/
public SieveOfEratosthenesBig(){ public SieveOfEratosthenesBig(){
dict = new HashMap<>(); dict = new HashMap<>();
possiblePrime = BigInteger.TWO; possiblePrime = BigInteger.TWO;
} }
/**
* Indicates whether there is a next prime number available.
*
* <p>
* This method always returns {@code true} as the iterator is designed to
* generate primes indefinitely.
* </p>
*
* @return {@code true}, as the iterator can generate an infinite number of primes
*/
@Override @Override
public boolean hasNext(){ public boolean hasNext(){
return true; return true;
} }
/**
* Returns the next prime number.
*
* <p>
* 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.
* </p>
*
* @return the next prime number
* @throws NoSuchElementException if the next prime cannot be represented by a {@code long}
*/
@Override @Override
public BigInteger next(){ public BigInteger next(){
BigInteger prime; BigInteger prime;
@@ -72,6 +114,10 @@ public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
//Delete the current entry //Delete the current entry
dict.remove(possiblePrime); 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 //Save that the number is a prime
prime = possiblePrime; prime = possiblePrime;
//Add the next entry to the prime dictionary //Add the next entry to the prime dictionary

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java //JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java
//Mattrixwv //Mattrixwv
// Created: 08-20-22 // Created: 08-20-22
//Modified: 04-13-23 //Modified: 08-11-24
//This class generates triangular numbers //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 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 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; import java.util.NoSuchElementException;
/**
* A generator for triangular numbers, which implements the {@link Iterator} interface.
*
* <p>
* Triangular numbers are figurate numbers that represent triangles. The n-th triangular number is given by
* the formula: T(n) = n(n + 1) / 2.
* </p>
*
* <p>
* This generator allows iteration over triangular numbers starting from the first.
* </p>
*/
public class TriangularNumberGenerator implements Iterator<Long>{ public class TriangularNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next triangular number from
*/
protected long num; protected long num;
/**
* Constructs a new TriangularNumberGenerator starting from the first triangular number.
*/
public TriangularNumberGenerator(){ public TriangularNumberGenerator(){
num = 1L; 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 @Override
public boolean hasNext(){ public boolean hasNext(){
return ((num * num) + num) > num; 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 @Override
public Long next(){ public Long next(){
if(!hasNext()){ if(!hasNext()){
@@ -50,6 +79,12 @@ public class TriangularNumberGenerator implements Iterator<Long>{
return newNum; 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){ public static boolean isTriangular(Long x){
Long n = Math.round((Math.sqrt(1.0D + (8L * x)) - 1L) / 2L); Long n = Math.round((Math.sqrt(1.0D + (8L * x)) - 1L) / 2L);
return (((n * n) + n) / 2L) == x; return (((n * n) + n) / 2L) == x;

View File

@@ -1,28 +1,7 @@
//JavaClasses/src/test/java/com/mattrixwv/TestTriple.java
//Mattrixwv
// Created: 08-20-22
//Modified: 04-13-23
/*
Copyright (C) 2023 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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.mattrixwv; package com.mattrixwv;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -40,6 +19,8 @@ public class TestTriple{
@Test @Test
public void testConstructor(){ public void testConstructor(){
triple = new Triple<>(1L, 2L, 3L);
assertEquals(1L, triple.getA()); assertEquals(1L, triple.getA());
assertEquals(2L, triple.getB()); assertEquals(2L, triple.getB());
assertEquals(3L, triple.getC()); assertEquals(3L, triple.getC());