1 Commits

Author SHA1 Message Date
d2385d5c27 Added deployment info 2021-07-03 15:58:09 -04:00
38 changed files with 1623 additions and 3430 deletions

5
.gitignore vendored
View File

@@ -1,7 +1,8 @@
#Ignore all vscode files
.vscode/*
#Ignore build files #Ignore build files
.classpath .classpath
.project .project
.settings/ .settings/
target/ target/
sonarBuild.ps1
sonarBuild.sh

View File

@@ -1,7 +0,0 @@
{
"sonarlint.connectedMode.project": {
"connectionId": "mattrixwvSonarqube",
"projectKey": "JavaClasses"
},
"java.configuration.updateBuildConfiguration": "automatic"
}

49
.vscode/tasks.json vendored
View File

@@ -1,49 +0,0 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "verify",
"type": "shell",
"command": "mvn -B verify",
"group": "build"
},
{
"label": "test",
"type": "shell",
"command": "mvn -B test",
"group": "test"
},
{
"label": "sonarqube build (Windows)",
"group": "build",
"type": "shell",
"command": "./sonarBuild.ps1",
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": []
},
{
"label": "sonarqube build (Linux)",
"group": "build",
"type": "shell",
"command": "./sonarBuild.sh",
"presentation": {
"echo": true,
"reveal": "always",
"focus": true,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": []
}
]
}

222
pom.xml
View File

@@ -4,70 +4,44 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<licenses> <groupId>mattrixwv</groupId>
<license>
<name>GNU LESSER GENERAL PUBLIC LICENSE</name>
<url>https://www.gnu.org/licenses/lgpl-3.0.en.html</url>
</license>
</licenses>
<developers>
<developer>
<name>Matthew Ellison</name>
<email>m_ellison@ymail.com</email>
<url>https://bitbucket.org/Mattrixwv</url>
</developer>
</developers>
<scm>
<connection>scm:git:git://bitbucket.org/Mattrixwv/JavaClasses.git</connection>
<developerConnection>scm:git:ssh://bitbucket.org:Mattrixwv/JavaClasses.git</developerConnection>
<url>https://bitbucket.org/Mattrixwv/JavaClasses/src</url>
</scm>
<groupId>com.mattrixwv</groupId>
<artifactId>myClasses</artifactId> <artifactId>myClasses</artifactId>
<version>1.3.6</version> <version>1.0-SNAPSHOT</version>
<name>myClasses</name> <name>myClasses</name>
<description>A grouping of functions that I've found useful</description> <!-- FIXME change it to the project's website -->
<url>www.mattrixwv.com</url> <url>http://www.example.com</url>
<properties> <properties>
<!--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> <maven.compiler.source>14</maven.compiler.source>
<maven.compiler.source>21</maven.compiler.source> <maven.compiler.target>14</maven.compiler.target>
<maven.compiler.target>21</maven.compiler.target> <bitbucket.maven.repository>file://D:/Programs/Java/JavaClasses/</bitbucket.maven.repository>
<java.version>21</java.version>
<!--Sonarqube-->
<sonar.java.source>21</sonar.java.source>
<sonar.dependencyCheck.jsonReportPath>target/dependency-check-report.json</sonar.dependencyCheck.jsonReportPath>
<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>junit</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit</artifactId>
<version>5.10.3</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<distributionManagement>
<repository>
<id>myClasses</id>
<url>${bitbucket.maven.repository}</url>
</repository>
</distributionManagement>
<build> <build>
<plugins> <plugins>
<!--Ensure maven is the correct version--> <!--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> <version>3.0.0-M3</version>
<executions> <executions>
<execution> <execution>
<id>enforce-maven</id> <id>enforce-maven</id>
@@ -77,185 +51,51 @@
<configuration> <configuration>
<rules> <rules>
<requireMavenVersion> <requireMavenVersion>
<version>3.8.6</version> <version>3.6.3</version>
</requireMavenVersion> </requireMavenVersion>
</rules> </rules>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.4.0</version> <version>3.1.0</version>
</plugin> </plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin> <plugin>
<artifactId>maven-resources-plugin</artifactId> <artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version> <version>3.2.0</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version> <version>3.8.1</version>
<configuration>
<release>${java.version}</release>
<compilerArgs>
<arg>-Xlint:all</arg>
</compilerArgs>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>3.3.1</version> <version>3.0.0-M5</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version> <version>3.2.0</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-install-plugin</artifactId> <artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version> <version>3.0.0-M1</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version> <version>3.0.0-M1</version>
</plugin> </plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin> <plugin>
<artifactId>maven-site-plugin</artifactId> <artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version> <version>3.9.1</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-project-info-reports-plugin</artifactId> <artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.2</version> <version>3.1.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.17.1</version>
<configuration>
<rulesUri>file://${session.executionRootDirectory}/version-rules.xml</rulesUri>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<!--Sonarqube-->
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>4.0.0.4121</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.12</version>
<executions>
<execution>
<id>jacoco-initialize</id>
<phase>none</phase>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>none</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>10.0.3</version>
<executions>
<execution>
<phase>none</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<formats>
<format>json</format>
<format>html</format>
</formats>
</configuration>
</plugin>
<!--Deployment-->
<plugin>
<groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId>
<version>0.5.0</version>
<extensions>true</extensions>
<configuration>
<publishingServerId>ossrh</publishingServerId>
</configuration>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.7.0</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterCloase>true</autoReleaseAfterCloase>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.3.1</version>
<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>
<version>3.8.0</version>
<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>
<version>3.2.4</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
<configuration>
<keyname>${gpg.keyname}</keyname>
</configuration>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>

View File

@@ -1,205 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 08-11-24
//This class contains algorithms for vectors that I've found it useful to keep around
/*
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
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;
import java.math.BigInteger;
import java.util.ArrayList;
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.
*
* <p>This class is not intended to be instantiated.</p>
*/
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
/**
* 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){
//Setup the variables
int sum = 0;
//Loop through every element in the list and add them together
for(int num : nums){
sum += num;
}
//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<Long> nums){
//Setup the variables
long sum = 0;
//Loop through every element in the list and add them together
for(long num : nums){
sum += num;
}
//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<BigInteger> nums){
//Setup the variables
BigInteger sum = BigInteger.ZERO;
//Loop through every element in the list and add them together
for(BigInteger num : nums){
sum = sum.add(num);
}
//Return the sum of all elements
return sum;
}
//?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){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
return 0;
}
//Setup the variables
int product = 1; //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(int num : nums){
product *= num;
}
//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<Long> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
return 0L;
}
//Setup the variables
long product = 1L; //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(long num : nums){
product *= num;
}
//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<BigInteger> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
return BigInteger.valueOf(0);
}
//Setup the variables
BigInteger product = BigInteger.valueOf(1); //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(BigInteger num : nums){
product = product.multiply(num);
}
//Return the product of all elements
return product;
}
//?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){
StringJoiner returnString = new StringJoiner(", ", "[", "]");
for(T obj : list){
returnString.add(obj.toString());
}
return returnString.toString();
}
//?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){
ArrayList<Integer> newList = new ArrayList<>(originalList.size());
for(Long num : originalList){
newList.add(num.intValue());
}
return newList;
}
}

View File

@@ -1,284 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/Stopwatch.java
//Matthew Ellison (Mattrixwv)
// Created: 03-01-19
//Modified: 08-11-24
//This file contains a class that is used to time the execution time of other programs
/*
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
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;
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{
/**
* 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
/**
* 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 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(){
if(startTime == null){
return 0L;
}
else if(stopTime == null){
return System.nanoTime() - startTime;
}
else{
return stopTime - startTime;
}
}
//?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
/**
* 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(){
//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
/**
* 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(){
//Set the stopTime as close to call time as possible
stopTime = System.nanoTime();
//If the startTime has not been set then reset stopTime
if(startTime == null){
stopTime = null;
}
}
//?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(){
//Make sure all variables are reset correctly
startTime = null;
stopTime = null;
}
//?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 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 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 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 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 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 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{
//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).
//This loop works down to seconds
TIME_RESOLUTION resolution;
for(resolution = TIME_RESOLUTION.NANOSECOND;(resolution.ordinal() < TIME_RESOLUTION.SECOND.ordinal()) && (duration >= 1000);resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1]){
duration /= 1000;
}
//Check if the duration needs reduced to minutes
if((duration >= 120) && (resolution == TIME_RESOLUTION.SECOND)){
//Reduce to minutes
duration /= 60;
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
//Check if the duration needs reduced to hours
if(duration >= 60){
//Reduce to hours
duration /= 60;
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
}
}
if(duration < 0){
resolution = TIME_RESOLUTION.ERROR;
}
//Turn the number into a string
int durationFraction = (int)Math.round(((duration % 1) * 1000));
String time = String.format("%d.%03d", duration.intValue(), durationFraction);
//Tack on the appropriate suffix for resolution
switch(resolution){
case NANOSECOND: time += " nanoseconds"; break;
case MICROSECOND: time += " microseconds"; break;
case MILLISECOND: time += " milliseconds"; break;
case SECOND: time += " seconds"; break;
case MINUTE: time += " minutes"; break;
case HOUR: time += " hours"; break;
case ERROR:
default: throw new InvalidResult("timeResolution was invalid");
}
//Return the string
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();
}
}

View File

@@ -1,178 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 08-11-24
//This class contains algorithms for strings that I've found it useful to keep around
/*
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
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;
import java.util.ArrayList;
import java.util.Collections;
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{
/**
* 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.
/**
* 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){
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){
ArrayList<String> perms = new ArrayList<>();
//Check if the number is out of bounds
if((num >= master.length()) || (num < 0)){
//Do nothing and return an empty arraylist
}
//If this is the last possible recurse just return the current string
else if(num == (master.length() - 1)){
perms.add(master);
}
//If there are more possible recurses, recurse with the current permutation
else{
ArrayList<String> temp = getPermutations(master, num + 1);
perms.addAll(temp);
//You need to swap the current letter with every possible letter after it
//The ones needed to swap before will happen automatically when the function recurses
for(int cnt = 1;(num + cnt) < master.length();++cnt){
master = swapString(master, num, (num + cnt));
temp = getPermutations(master, num + 1);
perms.addAll(temp);
master = swapString(master, num, (num + cnt));
}
//The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
if(num == 0){
Collections.sort(perms);
}
}
//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];
tempStr[first] = tempStr[second];
tempStr[second] = temp;
return new String(tempStr);
}
//?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
/**
* 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
/**
* 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){
return false;
}
//Return false if the wrong number of characters are in the string
if(str.length() != (top - bottom + 1)){
return false;
}
//Make sure that all of the needed characters are in the string exactly one time
for(char cnt = bottom;cnt <= top;++cnt){
if(findNumOccurrence(str, cnt) != 1){
return false;
}
}
//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');
}
}

View File

@@ -1,136 +0,0 @@
//JavaClasses/src/main/java/com/mattrixwv/Triple.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-11-24
//This class implements a triplet of variables
/*
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
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;
/**
* 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>{
/**
* 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.
*
* <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
public boolean equals(Object o){
if(this == o){
return true;
}
else if(o instanceof Triple<?, ?, ?> rightSide){
return (a.equals(rightSide.a) && b.equals(rightSide.b) && c.equals(rightSide.c));
}
else{
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.
*
* <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
public String toString(){
return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]";
}
}

View File

@@ -1,60 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java
//Matthew Ellison
// Created: 08-24-20
//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.
*
* <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{
/**
* 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.
*
* <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){
super(msg, cause);
}
}

View File

@@ -1,95 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java
//Matthew Ellison
// Created: 08-20-22
//Modified: 08-11-24
//This class generates hexagonal numbers
/*
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
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.generators;
import java.util.Iterator;
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>{
/**
* 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
if(!hasNext()){
throw new NoSuchElementException("Number overflow");
}
//Generate and return the hexagonal number
Long hexNum = ((2L * num * num) - num);
++num;
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;
}
}

View File

@@ -1,91 +0,0 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-11-24
//This class generates pentagonal numbers
/*
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
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.generators;
import java.util.Iterator;
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>{
/**
* 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()){
throw new NoSuchElementException("Number overflow");
}
long pentNum = ((3L * num * num) - num) / 2L;
++num;
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;
}
}

View File

@@ -1,126 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 08-11-24
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
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
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.generators;
import java.util.ArrayList;
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.
*
* <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>{
/**
* 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<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(){
dict = new HashMap<>();
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
public boolean hasNext(){
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
public Long next(){
long prime;
//If this is the first run just return 2
if(possiblePrime == 2){
prime = possiblePrime++;
return prime;
}
//Loop until you find a prime number
for(;dict.containsKey(possiblePrime);possiblePrime += 2){
//Create the next entry for all entries in the map
for(long num : dict.get(possiblePrime)){
if(!dict.containsKey(possiblePrime + num + num)){
dict.put(possiblePrime + num + num, new ArrayList<>(Arrays.asList(num)));
}
else{
dict.get(possiblePrime + num + num).add(num);
}
}
//Delete the current entry
dict.remove(possiblePrime);
}
//Protect against overflows
if(possiblePrime < 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
dict.put(prime * 3, new ArrayList<>(Arrays.asList(prime)));
//Move on to the next possible prime
possiblePrime += 2;
return prime;
}
}

View File

@@ -1,130 +0,0 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 08-11-24
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
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
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.generators;
import java.math.BigInteger;
import java.util.ArrayList;
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.
*
* <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>{
/**
* 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<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(){
dict = new HashMap<>();
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
public boolean hasNext(){
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
public BigInteger next(){
BigInteger prime;
if(possiblePrime.compareTo(BigInteger.TWO) <= 0){
//Return 2 and move to 3
prime = possiblePrime;
possiblePrime = possiblePrime.add(BigInteger.ONE);
return prime;
}
//Loop until you find a prime number
for(;dict.containsKey(possiblePrime);possiblePrime = possiblePrime.add(BigInteger.TWO)){
//Create the next entry for all entries in the map
for(BigInteger num : dict.get(possiblePrime)){
BigInteger loc = possiblePrime.add(num).add(num);
if(!dict.containsKey(loc)){
ArrayList<BigInteger> tempArray = new ArrayList<>(Arrays.asList(num));
dict.put(loc, tempArray);
}
else{
dict.get(loc).add(num);
}
}
//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
dict.put(prime.multiply(BigInteger.valueOf(3)), new ArrayList<>(Arrays.asList(prime)));
//Move on to the next possible prime
possiblePrime = possiblePrime.add(BigInteger.TWO);
return prime;
}
}

View File

@@ -1,92 +0,0 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-11-24
//This class generates triangular numbers
/*
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
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.generators;
import java.util.Iterator;
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>{
/**
* 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()){
throw new NoSuchElementException("Number overflow");
}
Long newNum = ((num * num) + num) / 2L;
++num;
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;
}
}

View File

@@ -0,0 +1,146 @@
//JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 07-03-21
//This class contains algorithms for vectors that I've found it useful to keep around
/*
Copyright (C) 2021 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 mattrixwv;
import java.math.BigInteger;
import java.util.ArrayList;
public class ArrayAlgorithms{
//This function returns the sum of all elements in the list
public static int getSum(ArrayList<Integer> nums){
//If a blank list was passed to the function return 0 as the sum
if(nums.size() == 0){
return 0;
}
//Setup the variables
int sum = 0;
//Loop through every element in the list and add them together
for(int num : nums){
sum += num;
}
//Return the sum of all elements
return sum;
}
public static long getLongSum(ArrayList<Long> nums){
//If a blank list was passed to the function return 0 as the sum
if(nums.size() == 0){
return 0L;
}
//Setup the variables
long sum = 0L;
//Loop through every element in the list and add them together
for(long num : nums){
sum += num;
}
//Return the sum of all elements
return sum;
}
public static BigInteger getBigSum(ArrayList<BigInteger> nums){
//If a blank list was passed to the function return 0 as the sum
if(nums.size() == 0){
return BigInteger.valueOf(0);
}
//Setup the variables
BigInteger sum = BigInteger.valueOf(0);
//Loop through every element in the list and add them together
for(BigInteger num : nums){
sum = sum.add(num);
}
//Return the sum of all elements
return sum;
}
//This function returns the product of all elements in the list
public static int getProd(ArrayList<Integer> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(nums.size() == 0){
return 0;
}
//Setup the variables
int product = 1; //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(int num : nums){
product *= num;
}
//Return the product of all elements
return product;
}
public static long getLongProd(ArrayList<Long> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(nums.size() == 0){
return 0L;
}
//Setup the variables
long product = 1L; //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(long num : nums){
product *= num;
}
//Return the product of all elements
return product;
}
public static BigInteger getBigProd(ArrayList<BigInteger> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(nums.size() == 0){
return BigInteger.valueOf(0);
}
//Setup the variables
BigInteger product = BigInteger.valueOf(1); //Start at 1 because x * 1 = x
//Loop through every element in the list and multiply them together
for(BigInteger num : nums){
product = product.multiply(num);
}
//Return the product of all elements
return product;
}
//Print a list
public static <T> String printList(ArrayList<T> list){
StringBuilder listString = new StringBuilder("[");
for(int cnt = 0;cnt < list.size();++cnt){
listString.append(list.get(cnt));
if(cnt < list.size() - 1){
listString.append(", ");
}
}
listString.append("]");
return listString.toString();
}
}

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: 08-11-24 //Modified: 07-03-21
//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) 2024 Matthew Ellison Copyright (C) 2021 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
@@ -19,76 +19,53 @@
You should have received a copy of the GNU Lesser General Public License 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/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.mattrixwv; package mattrixwv;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.InvalidParameterException; import java.security.InvalidParameterException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import com.mattrixwv.exceptions.InvalidResult; import 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{
/** //?This is here just to prove that templates exist and for a possible rewrite at a later time
* Private constructor to prevent instantiation public static <T> T getNum(T num1){
*/ return num1;
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
/**
* 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){
return ArrayAlgorithms.longToInt(getPrimes((long) 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. public static ArrayList<Integer> getPrimes(Integer goalNumber){
* ArrayList<Integer> primes = new ArrayList<Integer>(); //Holds the prime numbers
* @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){
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
//If the numebr is 0 or negative return an empty list //If the number is 0 or negative return an empty list
if(goalNumber <= 1){ if(goalNumber <= 1){
return primes; return primes;
} }
//Otherwise the number is at least 2, so 2 should be added to the list //Otherwise the number is at least 2, so 2 should be added to the list
else{ else{
primes.add(2L); primes.add(2);
} }
//We can now start at 3 and skip 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(int possiblePrime = 3;possiblePrime <= goalNumber;possiblePrime += 2){
//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));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt) <= topPossibleFactor.intValue());++primesCnt){ for(int primesCnt = 0;primes.get(primesCnt) <= topPossibleFactor.intValue();){
if((possiblePrime % primes.get(primesCnt)) == 0){ if((possiblePrime % primes.get(primesCnt)) == 0){
foundFactor = true; foundFactor = true;
break; break;
} }
else{
++primesCnt;
}
//Check if the index has gone out of range
if(primesCnt >= primes.size()){
break;
}
} }
//If you didn't find a factor then the current number must be prime //If you didn't find a factor then the current number must be prime
@@ -104,14 +81,53 @@ public class NumberAlgorithms{
Collections.sort(primes); Collections.sort(primes);
return primes; return primes;
} }
/** public static ArrayList<Long> getPrimes(Long goalNumber){
* Returns a list of all prime numbers less than or equal to the specified number. ArrayList<Long> primes = new ArrayList<Long>(); //Holds the prime numbers
* boolean foundFactor = false; //A flag for whether a factor of the current number has been found
* @param goalNumber the upper limit for generating prime numbers
* @return a list of prime numbers less than or equal to {@code goalNumber} //If the numebr is 0 or negative return an empty list
*/ if(goalNumber <= 1){
public static List<BigInteger> getPrimes(BigInteger goalNumber){ return primes;
ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers }
//Otherwise the number is at least 2, so 2 should be added to the list
else{
primes.add(2L);
}
//We cna now start at 3 and skipp 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));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;primes.get(primesCnt) <= topPossibleFactor.intValue();){
if((possiblePrime % primes.get(primesCnt)) == 0){
foundFactor = true;
break;
}
else{
++primesCnt;
}
//Check if the index has gone out of range
if(primesCnt >= primes.size()){
break;
}
}
//If you didn't find a factor then the current number must be prime
if(!foundFactor){
primes.add(possiblePrime);
}
else{
foundFactor = false;
}
}
//Sort the list before returning it
Collections.sort(primes);
return primes;
}
public static ArrayList<BigInteger> getPrimes(BigInteger goalNumber){
ArrayList<BigInteger> primes = new ArrayList<BigInteger>(); //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
//If the number is 1, 0 or negative return an empty list //If the number is 1, 0 or negative return an empty list
@@ -128,11 +144,18 @@ public class NumberAlgorithms{
//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
BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1)); BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt).compareTo(topPossibleFactor) <= 0);++primesCnt){ for(int primesCnt = 0;primes.get(primesCnt).compareTo(topPossibleFactor) <= 0;){
if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){ if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){
foundFactor = true; foundFactor = true;
break; break;
} }
else{
++primesCnt;
}
//Check if the index has gone out of range
if(primesCnt >= primes.size()){
break;
}
} }
//If you didn't find a factor then the current number must be prime //If you didn't find a factor then the current number must be prime
@@ -148,31 +171,58 @@ public class NumberAlgorithms{
Collections.sort(primes); Collections.sort(primes);
return primes; return primes;
} }
//This function gets a certain number of primes
public static ArrayList<Integer> getNumPrimes(Integer numberOfPrimes){
//?This function gets a certain number of primes ArrayList<Integer> primes = new ArrayList<Integer>(); //Holds the prime numbers
/**
* 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){
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){
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
//If the number is 0 or negative return an empty list //If the number is 0 or negative return an empty list
if(numberOfPrimes < 1){ if(numberOfPrimes <= 1){
return primes;
}
//Otherwise the number is at least 2, so 2 should be added to the list
else{
primes.add(2);
}
//We can now start at 3 and skip all even numbers, because they cannot be prime
for(int possiblePrime = 3;primes.size() < numberOfPrimes;possiblePrime += 2){
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;primes.get(primesCnt) <= topPossibleFactor.intValue();){
if((possiblePrime % primes.get(primesCnt)) == 0){
foundFactor = true;
break;
}
else{
++primesCnt;
}
//Check if the index has gone out of bounds
if(primesCnt >= primes.size()){
break;
}
}
//If you didn't find a factor then the current number must be prime
if(!foundFactor){
primes.add(possiblePrime);
}
else{
foundFactor = false;
}
}
//Sort the list before returning it
Collections.sort(primes);
return primes;
}
public static ArrayList<Long> getNumPrimes(Long numberOfPrimes){
ArrayList<Long> primes = new ArrayList<Long>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found
//If the number is 0 or negative return an empty list
if(numberOfPrimes <= 1){
return primes; return primes;
} }
//Otherwise the number is at least 2, so 2 should be added to the list //Otherwise the number is at least 2, so 2 should be added to the list
@@ -185,11 +235,18 @@ public class NumberAlgorithms{
//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));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt) <= topPossibleFactor.intValue());++primesCnt){ for(int primesCnt = 0;primes.get(primesCnt) <= topPossibleFactor.intValue();){
if((possiblePrime % primes.get(primesCnt)) == 0){ if((possiblePrime % primes.get(primesCnt)) == 0){
foundFactor = true; foundFactor = true;
break; break;
} }
else{
++primesCnt;
}
//Check if the index has gone out of bounds
if(primesCnt >= primes.size()){
break;
}
} }
//If you didn't find a factor then the current number must be prime //If you didn't find a factor then the current number must be prime
@@ -205,18 +262,12 @@ public class NumberAlgorithms{
Collections.sort(primes); Collections.sort(primes);
return primes; return primes;
} }
/** public static ArrayList<BigInteger> getNumPrimes(BigInteger numberOfPrimes){
* Returns a list of the specified number of prime numbers. ArrayList<BigInteger> primes = new ArrayList<BigInteger>(); //Holds the 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){
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
//If the number is 0 or negative return an empty list //If the number is 0 or negative return an empty list
if(numberOfPrimes.compareTo(BigInteger.valueOf(1)) < 0){ if(numberOfPrimes.compareTo(BigInteger.valueOf(1)) <= 0){
return primes; return primes;
} }
//Otherwise the number is at least 2, so 2 should be added to the list //Otherwise the number is at least 2, so 2 should be added to the list
@@ -229,11 +280,18 @@ public class NumberAlgorithms{
//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
BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1)); BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1));
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt).compareTo(topPossibleFactor) <= 0);++primesCnt){ for(int primesCnt = 0;primes.get(primesCnt).compareTo(topPossibleFactor) <= 0;){
if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){ if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){
foundFactor = true; foundFactor = true;
break; break;
} }
else{
++primesCnt;
}
//Check if the index has gone out of bounds
if(primesCnt >= primes.size()){
break;
}
} }
//If you didn't find a factor then the current number must be prime //If you didn't find a factor then the current number must be prime
@@ -249,15 +307,21 @@ public class NumberAlgorithms{
Collections.sort(primes); Collections.sort(primes);
return primes; return primes;
} }
//This function return true if the value passed to it is prime
public static boolean isPrime(int possiblePrime){
//?This function return true if the value passed to it is prime if(possiblePrime <= 3){
/** return possiblePrime > 1;
* Determines if a given number is prime. }
* else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){
* @param possiblePrime the number to be checked for primality return false;
* @return {@code true} if {@code possiblePrime} is a prime number, {@code false} otherwise }
*/ for(int cnt = 5;(cnt * cnt) <= possiblePrime;cnt += 6){
if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){
return false;
}
}
return true;
}
public static boolean isPrime(long possiblePrime){ public static boolean isPrime(long possiblePrime){
if(possiblePrime <= 3){ if(possiblePrime <= 3){
return possiblePrime > 1; return possiblePrime > 1;
@@ -272,12 +336,6 @@ 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;
@@ -292,30 +350,12 @@ public class NumberAlgorithms{
} }
return true; return true;
} }
//This function returns all factors of goalNumber
public static ArrayList<Integer> getFactors(Integer goalNumber) throws InvalidResult{
//?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{
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{
//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));
List<Long> primes = getPrimes(topPossiblePrime.longValue()); ArrayList<Integer> primes = getPrimes(topPossiblePrime.intValue());
ArrayList<Long> factors = new ArrayList<>(); ArrayList<Integer> factors = new ArrayList<Integer>();
//You need to step through each prime and see if it is a factor in the number //You need to step through each prime and see if it is a factor in the number
for(int cnt = 0;cnt < primes.size();){ for(int cnt = 0;cnt < primes.size();){
@@ -332,30 +372,58 @@ public class NumberAlgorithms{
} }
//If you didn't get any factors the number itself must be a prime //If you didn't get any factors the number itself must be a prime
if(factors.isEmpty()){ if(factors.size() == 0){
factors.add(goalNumber); factors.add(goalNumber);
goalNumber /= goalNumber; goalNumber /= goalNumber;
} }
//If for some reason the goalNumber is not 1 throw an error //If for some reason the goalNumber is not 1 throw an error
if(goalNumber != 1){ if(goalNumber != 1){
factors.add(goalNumber); throw new InvalidResult("The factor was not 1: " + goalNumber);
} }
//Return the list of factors //Return the list of factors
return factors; return factors;
} }
/** public static ArrayList<Long> getFactors(Long goalNumber) throws InvalidResult{
* 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{
//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); Double topPossiblePrime = Math.ceil(Math.sqrt(goalNumber));
List<BigInteger> primes = getPrimes(topPossiblePrime); ArrayList<Long> primes = getPrimes(topPossiblePrime.longValue());
ArrayList<BigInteger> factors = new ArrayList<>(); ArrayList<Long> factors = new ArrayList<Long>();
//You need to step through each prime and see if it is a factor in the number
for(int cnt = 0;cnt < primes.size();){
//If the prime is a factor you need to add it to the factor list
if((goalNumber % primes.get(cnt)) == 0){
factors.add(primes.get(cnt));
goalNumber /= primes.get(cnt);
}
//Otherwise advance the location in primes you are looking at
//By not advancing if the prime is a factor you allow for multiple of the same prime number as a factor
else{
++cnt;
}
}
//If you didn't get any factors the number itself must be a prime
if(factors.size() == 0){
factors.add(goalNumber);
goalNumber /= goalNumber;
}
//If for some reason the goalNumber is not 1 throw an error
if(goalNumber != 1){
throw new InvalidResult("The factor was not 1: " + goalNumber);
}
//Return the list of factors
return factors;
}
public static ArrayList<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
BigInteger topPossiblePrime = goalNumber.sqrt();
ArrayList<BigInteger> primes = getPrimes(topPossiblePrime);
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
//You need to step through each prime and see if it is a factor in the number //You need to step through each prime and see if it is a factor in the number
for(int cnt = 0;cnt < primes.size();){ for(int cnt = 0;cnt < primes.size();){
@@ -372,119 +440,141 @@ public class NumberAlgorithms{
} }
//If you didn't get any factors the number itself must be a prime //If you didn't get any factors the number itself must be a prime
if(factors.isEmpty()){ if(factors.size() == 0){
factors.add(goalNumber); factors.add(goalNumber);
goalNumber = goalNumber.divide(goalNumber); goalNumber.divide(goalNumber);
} }
//If for some reason the goalNumber is not 1 throw an error //If for some reason the goalNumber is not 1 throw an error
if(!goalNumber.equals(BigInteger.ONE)){ if(!goalNumber.equals(BigInteger.ONE)){
factors.add(goalNumber); throw new InvalidResult("The factor was not 1: " + goalNumber);
} }
//Return the list of factors //Return the list of factors
return factors; return factors;
} }
//This function returns all the divisors of goalNumber
public static ArrayList<Integer> getDivisors(Integer goalNumber){
//?This function returns all the divisors of goalNumber ArrayList<Integer> divisors = new ArrayList<Integer>();
/**
* 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){
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){
HashSet<Long> divisors = new HashSet<>();
//Start by checking that the number is positive //Start by checking that the number is positive
if(goalNumber <= 0){ if(goalNumber <= 0){
return new ArrayList<>(); return divisors;
} }
else{ //If the number is 1 return just itself
divisors.add(1L); else if(goalNumber == 1){
divisors.add(goalNumber); divisors.add(1);
return divisors;
} }
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
Double topPossibleDivisor = Math.ceil(Math.sqrt(goalNumber)); Double topPossibleDivisor = Math.ceil(Math.sqrt(goalNumber));
for(long possibleDivisor = 2L;possibleDivisor <= topPossibleDivisor;++possibleDivisor){ for(int possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//If you find one add it and the number it creates to the list //If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0){ if((goalNumber % possibleDivisor) == 0){
long possibleDivisor2 = goalNumber / possibleDivisor;
divisors.add(possibleDivisor); divisors.add(possibleDivisor);
divisors.add(possibleDivisor2); //Account for the possibility of sqrt(goalNumber) being a divisor
if(possibleDivisor != topPossibleDivisor.intValue()){
divisors.add(goalNumber / possibleDivisor);
}
//Take care of a few occations where a number was added twice
if(divisors.get(divisors.size() - 1) == (possibleDivisor + 1)){
++possibleDivisor;
}
} }
} }
ArrayList<Long> divisorList = new ArrayList<>(divisors);
//Sort the list before returning it for neatness //Sort the list before returning it for neatness
Collections.sort(divisorList); Collections.sort(divisors);
//Return the list //Return the list
return divisorList; return divisors;
} }
/** public static ArrayList<Long> getDivisors(Long goalNumber){
* Returns a list of divisors of the specified number. ArrayList<Long> divisors = new ArrayList<Long>();
* //Start by checking that the number is positive
* @param goalNumber the number to find divisors for if(goalNumber <= 0){
* @return a list of divisors of {@code goalNumber} return divisors;
*/ }
public static List<BigInteger> getDivisors(BigInteger goalNumber){ //If the number is 1 return just itself
HashSet<BigInteger> divisors = new HashSet<>(); else if(goalNumber == 1){
divisors.add(1L);
return divisors;
}
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
Double topPossibleDivisor = Math.ceil(Math.sqrt(goalNumber));
for(long possibleDivisor = 1L;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0){
divisors.add(possibleDivisor);
//Account for the possibility of sqrt(goalNumber) being a divisor
if(possibleDivisor != topPossibleDivisor.longValue()){
divisors.add(goalNumber / possibleDivisor);
}
//Take care of a few occations where a number was added twice
if(divisors.get(divisors.size() - 1) == (possibleDivisor + 1L)){
++possibleDivisor;
}
}
}
//Sort the list before returning it for neatness
Collections.sort(divisors);
//Return the list
return divisors;
}
public static ArrayList<BigInteger> getDivisors(BigInteger goalNumber){
ArrayList<BigInteger> divisors = new ArrayList<BigInteger>();
//Start by checking that the number is positive //Start by checking that the number is positive
if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){ if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){
return new ArrayList<>(); return divisors;
} }
else{ //If the number is 1 return just itself
else if(goalNumber.equals(BigInteger.valueOf(1))){
divisors.add(BigInteger.valueOf(1)); divisors.add(BigInteger.valueOf(1));
divisors.add(goalNumber); return divisors;
} }
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
BigInteger topPossibleDivisor = goalNumber.sqrt(); BigInteger topPossibleDivisor = goalNumber.sqrt();
for(BigInteger possibleDivisor = BigInteger.TWO;possibleDivisor.compareTo(topPossibleDivisor) <= 0;possibleDivisor = possibleDivisor.add(BigInteger.valueOf(1))){ for(BigInteger possibleDivisor = BigInteger.valueOf(1);possibleDivisor.compareTo(topPossibleDivisor) <= 0;possibleDivisor = possibleDivisor.add(BigInteger.valueOf(1))){
//If you find one add it and the number it creates to the list //If you find one add it and the number it creates to the list
if(goalNumber.mod(possibleDivisor).equals(BigInteger.valueOf(0))){ if(goalNumber.mod(possibleDivisor).equals(BigInteger.valueOf(0))){
BigInteger possibleDivisor2 = goalNumber.divide(possibleDivisor);
divisors.add(possibleDivisor); divisors.add(possibleDivisor);
divisors.add(possibleDivisor2); //Account for the possibility of sqrt(goalNumber) being a divisor
if(!possibleDivisor.equals(topPossibleDivisor)){
divisors.add(goalNumber.divide(possibleDivisor));
}
//Take care of a few occations where a number was added twice
if(divisors.get(divisors.size() - 1).equals(possibleDivisor.add(BigInteger.valueOf(1L)))){
possibleDivisor = possibleDivisor.add(BigInteger.valueOf(1));
}
} }
} }
ArrayList<BigInteger> divisorList = new ArrayList<>(divisors);
//Sort the list before returning it for neatness //Sort the list before returning it for neatness
Collections.sort(divisorList); Collections.sort(divisors);
//Return the list //Return the list
return divisorList; return divisors;
} }
//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); //Setup the variables
int[] fibNums = {1, 1, 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
//If the number is <= 0 return 0
if(goalSubscript <= 0){
return 0;
}
//Loop through the list, generating Fibonacci numbers until it finds the correct subscript
int fibLoc = 2;
for(fibLoc = 2;fibLoc < goalSubscript;++fibLoc){
fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3];
}
//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 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
@@ -495,7 +585,7 @@ public class NumberAlgorithms{
} }
//Loop through the list, generating Fibonacci numbers until it finds the correct subscript //Loop through the list, generating Fibonacci numbers until it finds the correct subscript
int fibLoc; int fibLoc = 2;
for(fibLoc = 2;fibLoc < goalSubscript;++fibLoc){ for(fibLoc = 2;fibLoc < goalSubscript;++fibLoc){
fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3]; fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3];
} }
@@ -503,12 +593,6 @@ 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
@@ -519,7 +603,7 @@ public class NumberAlgorithms{
} }
//Loop through the list, generating Fibonacci numbers until it finds the correct subscript //Loop through the list, generating Fibonacci numbers until it finds the correct subscript
int fibLoc; int fibLoc = 2;
for(fibLoc = 2;goalSubscript.compareTo(BigInteger.valueOf(fibLoc)) > 0;++fibLoc){ for(fibLoc = 2;goalSubscript.compareTo(BigInteger.valueOf(fibLoc)) > 0;++fibLoc){
fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3].add(fibNums[(fibLoc - 2) % 3]); fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3].add(fibNums[(fibLoc - 2) % 3]);
} }
@@ -527,28 +611,32 @@ 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];
} }
//This function returns a list of all Fibonacci numbers <= goalNumber
public static ArrayList<Integer> getAllFib(Integer 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){
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){
//Setup the variables //Setup the variables
ArrayList<Long> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers ArrayList<Integer> fibNums = new ArrayList<Integer>(); //A list to save the Fibonacci numbers
//If the number is <= 0 return an empty list
if(goalNumber <= 0){
return fibNums;
}
//This means that at least 2 1's are elements
fibNums.add(1);
fibNums.add(1);
//Loop to generate the rest of the Fibonacci numbers
while(fibNums.get(fibNums.size() - 1) <= goalNumber){
fibNums.add(fibNums.get(fibNums.size() - 1) + fibNums.get(fibNums.size() - 2));
}
//At this point the most recent number is > goalNumber, so remove it and return the rest of the list
fibNums.remove(fibNums.size() - 1);
return fibNums;
}
public static ArrayList<Long> getAllFib(Long goalNumber){
//Setup the variables
ArrayList<Long> fibNums = new ArrayList<Long>(); //A list to save the Fibonacci numbers
//If the number is <= 0 return an empty list //If the number is <= 0 return an empty list
if(goalNumber <= 0){ if(goalNumber <= 0){
@@ -568,15 +656,9 @@ public class NumberAlgorithms{
fibNums.remove(fibNums.size() - 1); fibNums.remove(fibNums.size() - 1);
return fibNums; return fibNums;
} }
/** public static ArrayList<BigInteger> getAllFib(BigInteger 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<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<BigInteger>(); //A list to save the Fibonacci numbers
//If the number is <= 0 return an empty list //If the number is <= 0 return an empty list
if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){ if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){
@@ -596,33 +678,27 @@ public class NumberAlgorithms{
fibNums.remove(fibNums.size() - 1); fibNums.remove(fibNums.size() - 1);
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); int fact = 1; //The value of the factorial
//If the number passed in is < 0 throw an exception
if(num < 0){
throw new InvalidParameterException("n! cannot be negative");
}
//Loop through every number up to and including num and add the product to the factorial
for(int cnt = 2;cnt <= num;++cnt){
fact *= cnt;
}
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 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
//If the number passed in is < 0 throw an exception //If the number passed in is < 0 throw an exception
if(num < 0){ if(num < 0){
throw new InvalidParameterException(FACTORIAL_NEGATIVE_MESSAGE); throw new InvalidParameterException("n! cannot be negative");
} }
//Loop through every number up to and including num and add the product to the factorial //Loop through every number up to and including num and add the product to the factorial
for(long cnt = 2L;cnt <= num;++cnt){ for(long cnt = 2L;cnt <= num;++cnt){
@@ -631,19 +707,12 @@ 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);
//If the number passed in is < 0 throw an exception //If the number passed in is < 0 throw an exception
if(num.compareTo(BigInteger.ZERO) < 0){ if(num.compareTo(BigInteger.ZERO) < 0){
throw new InvalidParameterException(FACTORIAL_NEGATIVE_MESSAGE); throw new InvalidParameterException("n! cannot be negative");
} }
//Loop through every number up to and including num and add the product to the factorial //Loop through every number up to and including num and add the product to the factorial
for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){ for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){
@@ -652,27 +721,18 @@ 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); while((num1 != 0) && (num2 != 0)){
if(num1 > num2){
num1 %= num2;
}
else{
num2 %= num1;
}
}
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 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){
@@ -684,13 +744,6 @@ 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){
@@ -702,24 +755,15 @@ 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 public static String toBin(int num){
/** //Convert the number to a binary string
* Converts a number to its binary equivalent. return Integer.toBinaryString(num);
* }
* @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

@@ -0,0 +1,82 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 06-30-21
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2021 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 mattrixwv;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class SieveOfEratosthenes implements Iterator<Long>{
long possiblePrime;
private Map<Long, ArrayList<Long>> dict;
public SieveOfEratosthenes(){
dict = new HashMap<Long, ArrayList<Long>>();
possiblePrime = 2;
}
@Override
public boolean hasNext(){
return true;
}
@Override
public Long next(){
long prime;
if(possiblePrime > 2){
//Loop until you find a prime number
for(;dict.containsKey(possiblePrime);possiblePrime += 2){
//Create the next entry for all entries in the map
for(long num : dict.get(possiblePrime)){
if(!dict.containsKey(possiblePrime + num + num)){
ArrayList<Long> tempArray = new ArrayList<Long>(Arrays.asList(num));
dict.put(possiblePrime + num + num, tempArray);
}
else{
dict.get(possiblePrime + num + num).add(num);
}
}
//Delete the current entry
dict.remove(possiblePrime);
}
//Save that the number is a prime
prime = possiblePrime;
//Add the next entry to the prime
if(!dict.containsKey(prime * 3)){
ArrayList<Long> tempArray = new ArrayList<Long>(Arrays.asList(prime));
dict.put(prime * 3, tempArray);
}
else{
dict.get(prime * 3).add(prime);
}
//Move on to the next possible prime
possiblePrime += 2;
}
else{
//Return 2 and move to 3
prime = possiblePrime++;
}
return prime;
}
}

View File

@@ -0,0 +1,85 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 06-30-21
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2021 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 mattrixwv;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
BigInteger possiblePrime;
private Map<BigInteger, ArrayList<BigInteger>> dict;
public SieveOfEratosthenesBig(){
dict = new HashMap<BigInteger, ArrayList<BigInteger>>();
possiblePrime = BigInteger.TWO;
}
@Override
public boolean hasNext(){
return true;
}
@Override
public BigInteger next(){
BigInteger prime;
if(possiblePrime.compareTo(BigInteger.TWO) > 0){
//Loop until you find a prime number
for(;dict.containsKey(possiblePrime);possiblePrime = possiblePrime.add(BigInteger.TWO)){
//Create the next entry for all entries in the map
for(BigInteger num : dict.get(possiblePrime)){
BigInteger loc = possiblePrime.add(num).add(num);
if(!dict.containsKey(loc)){
ArrayList<BigInteger> tempArray = new ArrayList<BigInteger>(Arrays.asList(num));
dict.put(loc, tempArray);
}
else{
dict.get(loc).add(num);
}
}
//Delete the current entry
dict.remove(possiblePrime);
}
//Save that the number is a prime
prime = possiblePrime;
BigInteger loc = prime.multiply(BigInteger.valueOf(3));
if(!dict.containsKey(loc)){
ArrayList<BigInteger> tempArray = new ArrayList<BigInteger>(Arrays.asList(prime));
dict.put(loc, tempArray);
}
else{
dict.get(loc).add(prime);
}
//Move on to the next possible prime
possiblePrime = possiblePrime.add(BigInteger.TWO);
}
else{
//Return 2 and move to 3
prime = possiblePrime;
possiblePrime = possiblePrime.add(BigInteger.ONE);
}
return prime;
}
}

View File

@@ -0,0 +1,153 @@
//JavaClasses/src/main/java/mattrixwv/Stopwatch.java
//Matthew Ellison (Mattrixwv)
// Created: 03-01-19
//Modified: 07-28-20
//This file contains a class that is used to time the execution time of other programs
/*
Copyright (C) 2020 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 mattrixwv;
import mattrixwv.exceptions.InvalidResult;
public class Stopwatch{
private Long startTime;
private Long stopTime;
//Constructor makes sure all values are set to defaults
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
private Long getTime(){
if(startTime == null){
return 0L;
}
else if(stopTime == null){
return System.nanoTime() - startTime;
}
else{
return stopTime - startTime;
}
}
//An enum that helps keep track of how many times the time has been reduced in the getStr function
private enum TIME_RESOLUTION{ NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, ERROR }
//Simulates starting a stopwatch by saving the time
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
public void stop(){
//Set the stopTime as close to call time as possible
stopTime = System.nanoTime();
//If the startTime has not been set then reset stopTime
if(startTime == null){
stopTime = null;
}
}
//Resets all variables in the stopwatch
public void reset(){
//Make sure all variables are reset correctly
startTime = null;
stopTime = null;
}
//Returns the time in nanoseconds
public double getNano() throws InvalidResult{
return getTime().doubleValue();
}
//Returns the time in microseconds
public double getMicro() throws InvalidResult{
return getTime().doubleValue() / 1000D;
}
//Returns the time in milliseconds
public double getMilli() throws InvalidResult{
return getTime().doubleValue() / 1000000D;
}
//Returns the time in seconds
public double getSecond() throws InvalidResult{
return getTime().doubleValue() / 1000000000D;
}
//Returns the time in minutes
public double getMinute() throws InvalidResult{
return getTime().doubleValue() / 60000000000D;
}
//Returns the time in hours
public double getHour() throws InvalidResult{
return getTime().doubleValue() / 3600000000000D;
}
//Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx)
public String getStr() throws InvalidResult{
//Get the current duration from time
return getStr(getTime().doubleValue());
}
public static String getStr(double nanoseconds) throws InvalidResult{
Double duration = nanoseconds;
//Reduce the number to the appropriate number of digits. (xxx.x).
//This loop works down to seconds
TIME_RESOLUTION resolution;
for(resolution = TIME_RESOLUTION.NANOSECOND;(resolution.ordinal() < TIME_RESOLUTION.SECOND.ordinal()) && (duration >= 1000);resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1]){
duration /= 1000;
}
//Check if the duration needs reduced to minutes
if((duration >= 120) && (resolution == TIME_RESOLUTION.SECOND)){
//Reduce to minutes
duration /= 60;
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
//Check if the duration needs reduced to hours
if(duration >= 60){
//Reduce to hours
duration /= 60;
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
}
}
//Turn the number into a string
int durationFraction = (int)Math.round(((duration % 1) * 1000));
String time = String.format("%d.%03d", duration.intValue(), durationFraction);
//Tack on the appropriate suffix for resolution
switch(resolution){
case NANOSECOND: time += " nanoseconds"; break;
case MICROSECOND: time += " microseconds"; break;
case MILLISECOND: time += " milliseconds"; break;
case SECOND: time += " seconds"; break;
case MINUTE: time += " minutes"; break;
case HOUR: time += " hours"; break;
case ERROR:
default: throw new InvalidResult("timeResolution was invalid");
}
//Return the string
return time;
}
@Override
public String toString(){
try{
return getStr();
}
catch(InvalidResult error){
return "There was an error in getStr(): " + error;
}
}
}

View File

@@ -0,0 +1,89 @@
//JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 07-03-21
//This class contains algorithms for strings that I've found it useful to keep around
/*
Copyright (C) 2021 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 mattrixwv;
import java.util.ArrayList;
import java.util.Collections;
public class StringAlgorithms{
//This is a function that creates all permutations of a string and returns a vector of those permutations.
public static ArrayList<String> getPermutations(String master){
return getPermutations(master, 0);
}
private static ArrayList<String> getPermutations(String master, int num){
ArrayList<String> perms = new ArrayList<String>();
//Check if the number is out of bounds
if((num >= master.length()) || (num < 0)){
//Do nothing and return an empty arraylist
}
//If this is the last possible recurse just return the current string
else if(num == (master.length() - 1)){
perms.add(master);
}
//If there are more possible recurses, recurse with the current permutation
else{
ArrayList<String> temp = getPermutations(master, num + 1);
perms.addAll(temp);
//You need to swap the current letter with every possible letter after it
//The ones needed to swap before will happen automatically when the function recurses
for(int cnt = 1;(num + cnt) < master.length();++cnt){
master = swapString(master, num, (num + cnt));
temp = getPermutations(master, num + 1);
perms.addAll(temp);
master = swapString(master, num, (num + cnt));
}
//The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
if(num == 0){
Collections.sort(perms);
}
}
//Return the arraylist that was built
return perms;
}
private static String swapString(String str, int first, int second){
char[] tempStr = str.toCharArray();
char temp = tempStr[first];
tempStr[first] = tempStr[second];
tempStr[second] = temp;
String swappedString = new String(tempStr);
return swappedString;
}
//This function returns 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
public static boolean isPalindrome(String str){
String rev = new StringBuilder(str).reverse().toString();
if(str.equals(rev)){
return true;
}
else{
return false;
}
}
}

View File

@@ -0,0 +1,17 @@
//JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java
//Matthew Ellison
// Created: 08-24-20
//Modified: 08-24-20
//This is an exception for an invalid result out of one of my algorithms
package mattrixwv.exceptions;
public class InvalidResult extends Exception{
private static final long serialVersionUID = 1L;
public InvalidResult(){
super();
}
public InvalidResult(String msg){
super(msg);
}
}

View File

@@ -1,142 +0,0 @@
//JavaClasses/src/test/java/mattrixwv/TestArrayAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 06-26-22
//This class contains tests for my array algorithms
/*
Copyright (C) 2022 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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class TestArrayAlgorithms{
@Test
public void testGetSum(){
//Test 1
int correctAnswer = 0;
List<Integer> numbers = new ArrayList<>();
int answer = ArrayAlgorithms.getSum(numbers);
assertEquals(correctAnswer, answer, "getSum int 1 failed");
//Test 2
correctAnswer = 118;
numbers = Arrays.asList(2, 2, 3, 3, 4, 4, 100);
answer = ArrayAlgorithms.getSum(numbers);
assertEquals(correctAnswer, answer, "getSum int 2 failed");
//Test 3
long longCorrectAnswer = 0;
List<Long> longNumbers = new ArrayList<>();
long longAnswer = ArrayAlgorithms.getLongSum(longNumbers);
assertEquals(longCorrectAnswer, longAnswer, "getSum long 1 failed");
//Test 4
longCorrectAnswer = 118;
longNumbers = Arrays.asList(2L, 2L, 3L, 3L, 4L, 4L, 100L);
longAnswer = ArrayAlgorithms.getLongSum(longNumbers);
assertEquals(longCorrectAnswer, longAnswer, "getSum long 2 failed");
//Test 5
BigInteger bigCorrectAnswer = BigInteger.ZERO;
List<BigInteger> bigNumbers = new ArrayList<>();
BigInteger bigAnswer = ArrayAlgorithms.getBigSum(bigNumbers);
assertEquals(bigCorrectAnswer, bigAnswer, "getSum BigInteger 1 failed");
//Test 6
bigCorrectAnswer = BigInteger.valueOf(118);
bigNumbers = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(3), BigInteger.valueOf(4), BigInteger.valueOf(4), BigInteger.valueOf(100));
bigAnswer = ArrayAlgorithms.getBigSum(bigNumbers);
assertEquals(bigCorrectAnswer, bigAnswer, "getSum BigInteger 2 failed");
}
@Test
public void testGetProd(){
//Test 1
int correctAnswer = 0;
List<Integer> numbers = new ArrayList<>();
int answer = ArrayAlgorithms.getProd(numbers);
assertEquals(correctAnswer, answer, "getProd int 1 failed");
//Test 2
correctAnswer = 57600;
numbers = Arrays.asList(2, 2, 3, 3, 4, 4, 100);
answer = ArrayAlgorithms.getProd(numbers);
assertEquals(correctAnswer, answer, "getProd int 2 failed");
//Test 3
long longCorrectAnswer = 0;
List<Long> longNumbers = new ArrayList<>();
long longAnswer = ArrayAlgorithms.getLongProd(longNumbers);
assertEquals(longCorrectAnswer, longAnswer, "getProd long 1 failed");
//Test 4
longCorrectAnswer = 57600L;
longNumbers = Arrays.asList(2L, 2L, 3L, 3L, 4L, 4L, 100L);
longAnswer = ArrayAlgorithms.getLongProd(longNumbers);
assertEquals(longCorrectAnswer, longAnswer, "getProd long 2 failed");
//Test 5
BigInteger bigCorrectAnswer = BigInteger.ZERO;
List<BigInteger> bigNumbers = new ArrayList<BigInteger>();
BigInteger bigAnswer = ArrayAlgorithms.getBigProd(bigNumbers);
assertEquals(bigCorrectAnswer, bigAnswer, "getProd BigInteger 1 failed");
//Test 6
bigCorrectAnswer = BigInteger.valueOf(57600);
bigNumbers = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(3), BigInteger.valueOf(4), BigInteger.valueOf(4), BigInteger.valueOf(100));
bigAnswer = ArrayAlgorithms.getBigProd(bigNumbers);
assertEquals(bigCorrectAnswer, bigAnswer, "getProd BigInteger 2 failed");
}
@Test
public void testPrintList(){
//Test 1
List<Integer> nums = new ArrayList<Integer>();
String correctAnswer = "[]";
String answer = ArrayAlgorithms.printList(nums);
assertEquals(correctAnswer, answer, "printList<Integer> 1 failed");
//Test 2
nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
correctAnswer = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]";
answer = ArrayAlgorithms.printList(nums);
assertEquals(correctAnswer, answer, "printList<Integer> 2 failed");
//Test 3
nums = Arrays.asList(-3, -2, -1, 0, 1, 2, 3);
correctAnswer = "[-3, -2, -1, 0, 1, 2, 3]";
answer = ArrayAlgorithms.printList(nums);
assertEquals(correctAnswer, answer, "printList<Integer> 3 failed");
//Test 4
List<String> strings = new ArrayList<String>();
correctAnswer = "[]";
answer = ArrayAlgorithms.printList(strings);
assertEquals(correctAnswer, answer, "printList<String> 1 failed");
//Test 5
strings = Arrays.asList("A", "B", "C");
correctAnswer = "[A, B, C]";
answer = ArrayAlgorithms.printList(strings);
assertEquals(correctAnswer, answer, "printList<String> 2 failed");
//Test 6
strings = new ArrayList<String>(Arrays.asList("abc", "def", "ghi"));
correctAnswer = "[abc, def, ghi]";
answer = ArrayAlgorithms.printList(strings);
assertEquals(correctAnswer, answer, "printList<String> 3 failed");
}
}

View File

@@ -1,626 +0,0 @@
//JavaClasses/src/test/java/mattrixwv/TestNumberAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 04-13-23
//This class contains tests for my number algorithms
/*
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.mattrixwv.exceptions.InvalidResult;
public class TestNumberAlgorithms{
@Test
public void testGetPrimes(){
//Test 1
List<Integer> correctAnswer = new ArrayList<>();
int topNum = 1;
List<Integer> answer = NumberAlgorithms.getPrimes(topNum);
assertEquals(correctAnswer, answer, "getPrimes int 1 failed");
//Test 2
correctAnswer = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
topNum = 100;
answer = NumberAlgorithms.getPrimes(topNum);
assertEquals(correctAnswer, answer, "getPrimes int 2 failed");
//Test 3
List<Long> longCorrectAnswer = new ArrayList<>();
long longTopNum = 0;
List<Long> longAnswer = NumberAlgorithms.getPrimes(longTopNum);
assertEquals(longCorrectAnswer, longAnswer, "getPrimes long 1 failed");
//Test 4
longCorrectAnswer = Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L);
longTopNum = 100;
longAnswer = NumberAlgorithms.getPrimes(longTopNum);
assertEquals(longCorrectAnswer, longAnswer, "getPrimes long 2 failed");
//Test 5
List<BigInteger> bigCorrectAnswer = new ArrayList<>();
BigInteger bigTopNum = BigInteger.ZERO;
List<BigInteger> bigAnswer = NumberAlgorithms.getPrimes(bigTopNum);
assertEquals(bigCorrectAnswer, bigAnswer, "getPrimes BigInteger 1 failed");
//Test 6
bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97));
bigTopNum = BigInteger.valueOf(100);
bigAnswer = NumberAlgorithms.getPrimes(bigTopNum);
assertEquals(bigCorrectAnswer, bigAnswer, "getPrimes BigInteger 2 failed");
}
@Test
public void testGetNumPrimes(){
//Test 1
List<Integer> correctAnswer = new ArrayList<>();
int numPrimes = 0;
List<Integer> answer = NumberAlgorithms.getNumPrimes(numPrimes);
assertEquals(correctAnswer, answer, "getNumPrimes int 1 failed");
//Test 2
correctAnswer = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
numPrimes = 25;
answer = NumberAlgorithms.getNumPrimes(numPrimes);
assertEquals(correctAnswer, answer, "getNumPrimes int 2 failed");
//Test 3
List<Long> longCorrectAnswer = new ArrayList<>();
long longNumPrimes = 0;
List<Long> longAnswer = NumberAlgorithms.getNumPrimes(longNumPrimes);
assertEquals(longCorrectAnswer, longAnswer, "getNumPrimes long 1 failed");
//Test 4
longCorrectAnswer = Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L);
longNumPrimes = 25;
longAnswer = NumberAlgorithms.getNumPrimes(longNumPrimes);
assertEquals(longCorrectAnswer, longAnswer, "getNumPrimes long 2 failed");
//Test 5
List<BigInteger> bigCorrectAnswer = new ArrayList<>();
BigInteger bigNumPrimes = BigInteger.ZERO;
List<BigInteger> bigAnswer = NumberAlgorithms.getNumPrimes(bigNumPrimes);
assertEquals(bigCorrectAnswer, bigAnswer, "getNumPrimes BigInteger 1 failed");
//Test 6
bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97));
bigNumPrimes = BigInteger.valueOf(25);
bigAnswer = NumberAlgorithms.getNumPrimes(bigNumPrimes);
assertEquals(bigCorrectAnswer, bigAnswer, "getNumPrimes BigInteger 2 failed");
}
@Test
public void testIsPrime(){
//Test 1
int num = 4;
boolean correctAnswer = false;
boolean answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 2
num = 15;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 3
num = 97;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 4
num = 1;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 5
num = 2;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 6
num = 49;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 7
num = 55;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals(correctAnswer, answer);
//Test 8
long longNum = 4L;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 9
longNum = 15L;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 10
longNum = 97L;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 11
longNum = 1L;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 12
longNum = 2L;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 13
longNum = 49L;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 14
longNum = 55L;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals(correctAnswer, answer);
//Test 15
BigInteger bigNum = BigInteger.valueOf(4);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 16
bigNum = BigInteger.valueOf(15);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 17
bigNum = BigInteger.valueOf(97);
correctAnswer = true;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 18
bigNum = BigInteger.valueOf(1);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 19
bigNum = BigInteger.valueOf(2);
correctAnswer = true;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 20
bigNum = BigInteger.valueOf(49);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
//Test 21
bigNum = BigInteger.valueOf(55);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals(correctAnswer, answer);
}
@Test
public void testGetFactors() throws InvalidResult{
//Test 1
List<Integer> correctAnswer = Arrays.asList(2, 2, 5, 5);
int number = 100;
List<Integer> answer = NumberAlgorithms.getFactors(number);
assertEquals(correctAnswer, answer);
//Test 2
correctAnswer = Arrays.asList(2, 7, 7);
number = 98;
answer = NumberAlgorithms.getFactors(number);
assertEquals(correctAnswer, answer);
//Test 3
correctAnswer = Arrays.asList(7);
number = 7;
answer = NumberAlgorithms.getFactors(number);
assertEquals(correctAnswer, answer);
//Test 4
correctAnswer = Arrays.asList(2, 5);
number = 10;
answer = NumberAlgorithms.getFactors(number);
assertEquals(correctAnswer, answer);
//Test 5
List<Long> longCorrectAnswer = Arrays.asList(2L, 2L, 5L, 5L);
long longNumber = 100L;
List<Long> longAnswer = NumberAlgorithms.getFactors(longNumber);
assertEquals(longCorrectAnswer, longAnswer);
//Test 6
longCorrectAnswer = Arrays.asList(2L, 7L, 7L);
longNumber = 98;
longAnswer = NumberAlgorithms.getFactors(longNumber);
assertEquals(longCorrectAnswer, longAnswer);
//Test 7
longCorrectAnswer = Arrays.asList(7L);
longNumber = 7;
longAnswer = NumberAlgorithms.getFactors(longNumber);
assertEquals(longCorrectAnswer, longAnswer);
//Test 8
longCorrectAnswer = Arrays.asList(2L, 5L);
longNumber = 10L;
longAnswer = NumberAlgorithms.getFactors(longNumber);
assertEquals(longCorrectAnswer, longAnswer);
//Test 9
List<BigInteger> bigCorrectAnswer = Arrays.asList(BigInteger.TWO, BigInteger.TWO, BigInteger.valueOf(5), BigInteger.valueOf(5));
BigInteger bigNumber = BigInteger.valueOf(100);
List<BigInteger> bigAnswer = NumberAlgorithms.getFactors(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer);
//Test 10
bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(7), BigInteger.valueOf(7));
bigNumber = BigInteger.valueOf(98);
bigAnswer = NumberAlgorithms.getFactors(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer);
//Test 11
bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(7));
bigNumber = BigInteger.valueOf(7);
bigAnswer = NumberAlgorithms.getFactors(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer);
//Test 12
bigCorrectAnswer = Arrays.asList(BigInteger.TWO, BigInteger.valueOf(5));
bigNumber = BigInteger.valueOf(10);
bigAnswer = NumberAlgorithms.getFactors(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetDivisors(){
//Test 1
List<Integer> correctAnswer = Arrays.asList(1, 2, 4, 5, 10, 20, 25, 50, 100);
int topNum = 100;
List<Integer> answer = NumberAlgorithms.getDivisors(topNum);
assertEquals(correctAnswer, answer, "getDivisors int 1 failed");
//Test 2
correctAnswer = Arrays.asList(1, 2, 3, 6);
topNum = 6;
answer = NumberAlgorithms.getDivisors(topNum);
assertEquals(correctAnswer, answer, "getDivisors int 2 failed");
//Test 3
correctAnswer = new ArrayList<>();
topNum = -1;
answer = NumberAlgorithms.getDivisors(topNum);
assertEquals(correctAnswer, answer, "getDivisors int 3 failed");
//Test 4
List<Long> longCorrectAnswer = Arrays.asList(1L, 2L, 4L, 5L, 10L, 20L, 25L, 50L, 100L);
long longTopNum = 100;
List<Long> longAnswer = NumberAlgorithms.getDivisors(longTopNum);
assertEquals(longCorrectAnswer, longAnswer, "getDivisors long 1 failed");
//Test 5
longCorrectAnswer = Arrays.asList(1L, 2L, 3L, 6L);
longTopNum = 6;
longAnswer = NumberAlgorithms.getDivisors(longTopNum);
assertEquals(longCorrectAnswer, longAnswer, "getDivisors long 2 failed");
//Test 6
longCorrectAnswer = new ArrayList<>();
longTopNum = -1;
longAnswer = NumberAlgorithms.getDivisors(longTopNum);
assertEquals(longCorrectAnswer, longAnswer, "getDivisors long 3 failed");
//Test 7
List<BigInteger> bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(2), BigInteger.valueOf(4), BigInteger.valueOf(5), BigInteger.valueOf(10), BigInteger.valueOf(20), BigInteger.valueOf(25), BigInteger.valueOf(50), BigInteger.valueOf(100));
BigInteger bigTopNum = BigInteger.valueOf(100);
List<BigInteger> bigAnswer = NumberAlgorithms.getDivisors(bigTopNum);
assertEquals(bigCorrectAnswer, bigAnswer, "getDivisors BigInteger 1 failed");
//Test 8
bigCorrectAnswer = Arrays.asList(BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), BigInteger.valueOf(6));
bigTopNum = BigInteger.valueOf(6);
bigAnswer = NumberAlgorithms.getDivisors(bigTopNum);
assertEquals(bigCorrectAnswer, bigAnswer, "getDivisors BigInteger 2 failed");
//Test 9
bigCorrectAnswer = new ArrayList<>();
bigTopNum = BigInteger.valueOf(-1);
bigAnswer = NumberAlgorithms.getDivisors(bigTopNum);
assertEquals(bigCorrectAnswer, bigAnswer, "getDivisors BigInteger 3 failed");
}
@Test
public void testGetFib(){
//Test 1
int correctAnswer = 0;
int number = 0;
int answer = NumberAlgorithms.getFib(number);
assertEquals(correctAnswer, answer, "getFib int 1 failed");
//Test 2
correctAnswer = 144;
number = 12;
answer = NumberAlgorithms.getFib(number);
assertEquals(correctAnswer, answer, "getFib int 2 failed");
//Test 3
correctAnswer = 6765;
number = 20;
answer = NumberAlgorithms.getFib(number);
assertEquals(correctAnswer, answer, "getFib int 3 failed");
//Test 4
long longCorrectAnswer = 0;
long longNumber = 0;
long longAnswer = NumberAlgorithms.getFib(longNumber);
assertEquals(longCorrectAnswer, longAnswer, "getFib long 1 failed");
//Test 5
longCorrectAnswer = 144;
longNumber = 12;
longAnswer = NumberAlgorithms.getFib(longNumber);
assertEquals(longCorrectAnswer, longAnswer, "getFib long 2 failed");
//Test 6
longCorrectAnswer = 6765;
longNumber = 20;
longAnswer = NumberAlgorithms.getFib(longNumber);
assertEquals(longCorrectAnswer, longAnswer, "getFib long 3 failed");
//Test 7
BigInteger bigCorrectAnswer = BigInteger.ZERO;
BigInteger bigNumber = BigInteger.ZERO;
BigInteger bigAnswer = NumberAlgorithms.getFib(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getFib BigInteger 1 failed");
//Test 8
bigCorrectAnswer = BigInteger.valueOf(144);
bigNumber = BigInteger.valueOf(12);
bigAnswer = NumberAlgorithms.getFib(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getFib BigInteger 2 failed");
//Test 9
bigCorrectAnswer = BigInteger.valueOf(6765);
bigNumber = BigInteger.valueOf(20);
bigAnswer = NumberAlgorithms.getFib(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getFib BigInteger 3 failed");
//Test 10
bigCorrectAnswer = new BigInteger("1070066266382758936764980584457396885083683896632151665013235203375314520604694040621889147582489792657804694888177591957484336466672569959512996030461262748092482186144069433051234774442750273781753087579391666192149259186759553966422837148943113074699503439547001985432609723067290192870526447243726117715821825548491120525013201478612965931381792235559657452039506137551467837543229119602129934048260706175397706847068202895486902666185435124521900369480641357447470911707619766945691070098024393439617474103736912503231365532164773697023167755051595173518460579954919410967778373229665796581646513903488154256310184224190259846088000110186255550245493937113651657039447629584714548523425950428582425306083544435428212611008992863795048006894330309773217834864543113205765659868456288616808718693835297350643986297640660000723562917905207051164077614812491885830945940566688339109350944456576357666151619317753792891661581327159616877487983821820492520348473874384736771934512787029218636250627816");
bigNumber = BigInteger.valueOf(4782);
bigAnswer = NumberAlgorithms.getFib(bigNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getFib BigInteger 4 failed");
}
@Test
public void testGetAllFib(){
//Test 1
List<Integer> correctAnswer = new ArrayList<>();
int highestNumber = 0;
List<Integer> answer = NumberAlgorithms.getAllFib(highestNumber);
assertEquals(correctAnswer, answer, "getAllFib int 1 failed");
//Test 2
correctAnswer = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89);
highestNumber = 100;
answer = NumberAlgorithms.getAllFib(highestNumber);
assertEquals(correctAnswer, answer, "getAllFib int 2 failed");
//Test 3
correctAnswer = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987);
highestNumber = 1000;
answer = NumberAlgorithms.getAllFib(highestNumber);
assertEquals(correctAnswer, answer, "getAllFib int 3 failed");
//Test 4
List<Long> longCorrectAnswer = new ArrayList<>();
long longHighestNumber = 0;
List<Long> longAnswer = NumberAlgorithms.getAllFib(longHighestNumber);
assertEquals(longCorrectAnswer, longAnswer, "getAllFib long 1 failed");
//Test 5
longCorrectAnswer = Arrays.asList(1L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L);
longHighestNumber = 100;
longAnswer = NumberAlgorithms.getAllFib(longHighestNumber);
assertEquals(longCorrectAnswer, longAnswer, "getAllFib long 2 failed");
//Test 6
longCorrectAnswer = Arrays.asList(1L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L);
longHighestNumber = 1000L;
longAnswer = NumberAlgorithms.getAllFib(longHighestNumber);
assertEquals(longCorrectAnswer, longAnswer, "getAllFib long 3 failed");
//Test 7
List<BigInteger> bigCorrectAnswer = new ArrayList<>();
BigInteger bigHighestNumber = BigInteger.ZERO;
List<BigInteger> bigAnswer = NumberAlgorithms.getAllFib(bigHighestNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "gitAllFib BigInteger 1 failed");
//Test 8
bigCorrectAnswer = Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(8), BigInteger.valueOf(13), BigInteger.valueOf(21), BigInteger.valueOf(34), BigInteger.valueOf(55), BigInteger.valueOf(89));
bigHighestNumber = BigInteger.valueOf(100);
bigAnswer = NumberAlgorithms.getAllFib(bigHighestNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getAllFib BigInteger 2 failed");
//Test 9
bigCorrectAnswer = Arrays.asList(BigInteger.ONE, BigInteger.ONE, BigInteger.TWO, BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(8), BigInteger.valueOf(13), BigInteger.valueOf(21), BigInteger.valueOf(34), BigInteger.valueOf(55), BigInteger.valueOf(89), BigInteger.valueOf(144), BigInteger.valueOf(233), BigInteger.valueOf(377), BigInteger.valueOf(610), BigInteger.valueOf(987));
bigHighestNumber = BigInteger.valueOf(1000);
bigAnswer = NumberAlgorithms.getAllFib(bigHighestNumber);
assertEquals(bigCorrectAnswer, bigAnswer, "getAllFib BigInteger 3 failed");
}
@Test
public void testFactorial(){
//Test 1
Exception error = assertThrows(InvalidParameterException.class, () -> {
NumberAlgorithms.factorial(-1);
});
assertEquals(NumberAlgorithms.FACTORIAL_NEGATIVE_MESSAGE, error.getMessage());
//Test 2
int correctAnswer = 720;
int number = 6;
int answer = NumberAlgorithms.factorial(number);
assertEquals(correctAnswer, answer, "factorial int 1 failed");
//Test 3
correctAnswer = 479001600;
number = 12;
answer = NumberAlgorithms.factorial(number);
assertEquals(correctAnswer, answer, "factorial int 2 failed");
//Test 4
error = assertThrows(InvalidParameterException.class, () -> {
NumberAlgorithms.factorial(-1L);
});
assertEquals(NumberAlgorithms.FACTORIAL_NEGATIVE_MESSAGE, error.getMessage());
//Test 5
long correctAnswerLong = 720L;
long numberLong = 6L;
long answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals(correctAnswerLong, answerLong, "factorial long 1 failed");
//Test 6
correctAnswerLong = 479001600L;
numberLong = 12L;
answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals(correctAnswerLong, answerLong, "factorial long 2 failed");
//Test 7
correctAnswerLong = 2432902008176640000L;
numberLong = 20L;
answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals(correctAnswerLong, answerLong, "factorial long 3 failed");
//Test 8
final BigInteger exceptionNumberBig = BigInteger.valueOf(-1);
error = assertThrows(InvalidParameterException.class, () -> {
NumberAlgorithms.factorial(exceptionNumberBig);
});
assertEquals(NumberAlgorithms.FACTORIAL_NEGATIVE_MESSAGE, error.getMessage());
//Test 9
BigInteger correctAnswerBig = BigInteger.valueOf(720L);
BigInteger numberBig = BigInteger.valueOf(6);
BigInteger answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals(correctAnswerBig, answerBig, "factorial BigInteger 1 failed");
//Test 10
correctAnswerBig = BigInteger.valueOf(479001600L);
numberBig = BigInteger.valueOf(12);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals(correctAnswerBig, answerBig, "factorial BigInteger 2 failed");
//Test 11
correctAnswerBig = BigInteger.valueOf(2432902008176640000L);
numberBig = BigInteger.valueOf(20L);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals(correctAnswerBig, answerBig, "factorial BigInteger 3 failed");
//Test 12
correctAnswerBig = new BigInteger("265252859812191058636308480000000");
numberBig = BigInteger.valueOf(30L);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals(correctAnswerBig, answerBig, "factorial BigInteger 4 failed");
}
@Test
public void testGCD(){
//Test 1
int num1 = 2;
int num2 = 3;
int correctAnswer = 1;
int answer = NumberAlgorithms.gcd(num1, num2);
assertEquals(correctAnswer, answer, "GCD int 1 failed");
//Test 2
num1 = 1000;
num2 = 575;
correctAnswer = 25;
answer = NumberAlgorithms.gcd(num1, num2);
assertEquals(correctAnswer, answer, "GCD int 2 failed");
//Test 3
num1 = 1000;
num2 = 1000;
correctAnswer = 1000;
answer = NumberAlgorithms.gcd(num1, num2);
assertEquals(correctAnswer, answer, "GCD int 3 failed");
//Test 4
long longNum1 = 2;
long longNum2 = 3;
long longCorrectAnswer = 1;
long longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals(longCorrectAnswer, longAnswer, "GCD long 1 failed");
//Test 5
longNum1 = 1000;
longNum2 = 575;
longCorrectAnswer = 25;
longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals(longCorrectAnswer, longAnswer, "GCD long 2 failed");
//Test 6
longNum1 = 1000;
longNum2 = 1000;
longCorrectAnswer = 1000;
longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals(longCorrectAnswer, longAnswer, "GCD long 3 failed");
//Test 7
BigInteger bigNum1 = BigInteger.TWO;
BigInteger bigNum2 = BigInteger.valueOf(3);
BigInteger bigCorrectAnswer = BigInteger.ONE;
BigInteger bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals(bigCorrectAnswer, bigAnswer, "GCD BigInteger 1 failed");
//Test 8
bigNum1 = BigInteger.valueOf(1000);
bigNum2 = BigInteger.valueOf(575);
bigCorrectAnswer = BigInteger.valueOf(25);
bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals(bigCorrectAnswer, bigAnswer, "GCD BigInteger 2 failed");
//Test 9
bigNum1 = BigInteger.valueOf(1000);
bigNum2 = BigInteger.valueOf(1000);
bigCorrectAnswer = BigInteger.valueOf(1000);
bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals(bigCorrectAnswer, bigAnswer, "GCD BigInteger 3 failed");
}
@Test
public void testToBin(){
//Test 1
int num = 7;
String correctAnswer = "111";
String answer = NumberAlgorithms.toBin(num);
assertEquals(correctAnswer, answer, "toBin 1 failed");
//Test 2
num = 0;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(num);
assertEquals(correctAnswer, answer, "toBin 2 failed");
//Test 3
num = 1000000;
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(num);
assertEquals(correctAnswer, answer, "toBin 3 failed");
//Test 4
long longNum = 7;
correctAnswer = "111";
answer = NumberAlgorithms.toBin(longNum);
assertEquals(correctAnswer, answer, "toBin long 1 failed");
//Test 5
longNum = 0;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(longNum);
assertEquals(correctAnswer, answer, "toBin long 2 failed");
//Test 6
longNum = 1000000;
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(longNum);
assertEquals(correctAnswer, answer, "toBin long 3 failed");
//Test 7
BigInteger bigNum = BigInteger.valueOf(7);
correctAnswer = "111";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals(correctAnswer, answer, "toBin big 1 failed");
//Test 8
bigNum = BigInteger.ZERO;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals(correctAnswer, answer, "toBin big 2 failed");
//Test 9
bigNum = BigInteger.valueOf(1000000);
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals(correctAnswer, answer, "toBin big 3 failed");
}
}

View File

@@ -1,130 +0,0 @@
//JavaClasses/src/test/java/mattrixwv/TestStringAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 04-13-23
//This class contains tests for my number algorithms
/*
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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class TestStringAlgorithms{
@Test
public void testGetPermutations(){
//Test 1
String permString = "012";
List<String> correctAnswer = Arrays.asList("012", "021", "102", "120", "201", "210");
List<String> answer = StringAlgorithms.getPermutations(permString);
assertEquals(correctAnswer, answer, "getPermutations failed");
//Test 2
permString = "012";
correctAnswer = new ArrayList<>();
answer = StringAlgorithms.getPermutations(permString, 4);
assertEquals(correctAnswer, answer);
//Test 3
permString = "012";
correctAnswer = new ArrayList<>();
answer = StringAlgorithms.getPermutations(permString, -1);
assertEquals(correctAnswer, answer);
}
@Test
public void testFindNumOccurrence(){
//Test 1
String testString = "abcdefgdd";
char testChar = 'a';
long correctAnswer = 1;
long answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer, "FindNumOccurrence 1 failed");
//Test 2
testChar = 'd';
correctAnswer = 3;
answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer, "FindNumOccurrence 2 failed");
//Test 3
testChar = 'h';
correctAnswer = 0;
answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals(correctAnswer, answer, "FindNumOccurrence 3 failed");
}
@Test
public void testIsPalindrome(){
//Test 1
String str = "101";
boolean correctAnswer = true;
boolean answer = StringAlgorithms.isPalindrome(str);
assertEquals(correctAnswer, answer, "isPalindrome 1 failed");
//Test 2
str = "100";
correctAnswer = false;
answer = StringAlgorithms.isPalindrome(str);
assertEquals(correctAnswer, answer, "isPalindrome 2 failed");
//Test 3
str = "";
correctAnswer = true;
answer = StringAlgorithms.isPalindrome(str);
assertEquals(correctAnswer, answer, "isPalindrome 3 failed");
}
@Test
public void testIsPandigital(){
//Test 1
String num = "123456789";
boolean correctAnswer = true;
boolean answer = StringAlgorithms.isPandigital(num);
assertEquals(correctAnswer, answer, "isPandigital 1 failed");
//Test 2
num = "123";
correctAnswer = true;
answer = StringAlgorithms.isPandigital(num, '1', '3');
assertEquals(correctAnswer, answer, "isPandigital 2 failed");
//Test 3
num = "123";
correctAnswer = false;
answer = StringAlgorithms.isPandigital(num);
assertEquals(correctAnswer, answer, "isPandigital 3 failed");
//Test 4
num = "123";
correctAnswer = false;
answer = StringAlgorithms.isPandigital(num, '3', '1');
assertEquals(correctAnswer, answer, "isPandigital 4 failed");
//Test 5
num = "1";
correctAnswer = true;
answer = StringAlgorithms.isPandigital(num, '1', '1');
assertEquals(correctAnswer, answer, "isPandigital 5 failed");
//Test 6
num = "112";
correctAnswer = false;
answer = StringAlgorithms.isPandigital(num, '1', '3');
assertEquals(correctAnswer, answer, "isPandigital 6 failed");
}
}

View File

@@ -1,87 +0,0 @@
//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;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestTriple{
private Triple<Long, Long, Long> triple;
@BeforeEach
public void setup(){
triple = new Triple<>(1L, 2L, 3L);
}
@Test
public void testConstructor(){
assertEquals(1L, triple.getA());
assertEquals(2L, triple.getB());
assertEquals(3L, triple.getC());
}
@Test
public void testGetters(){
assertEquals(1L, triple.getA());
assertEquals(2L, triple.getB());
assertEquals(3L, triple.getC());
}
@Test
public void testEquals(){
Triple<Long, Long, Long> triple2 = new Triple<>(1L, 2L, 3L);
Triple<Long, Long, Long> triple3 = new Triple<>(3L, 2L, 3L);
Triple<Long, Long, Long> triple4 = new Triple<>(1L, 3L, 3L);
Triple<Long, Long, Long> triple5 = new Triple<>(1L, 2L, 1L);
Triple<Long, Long, Long> triple6 = new Triple<>(2L, 1L, 3L);
Triple<Long, Long, Long> triple7 = new Triple<>(3L, 2L, 1L);
Triple<Long, Long, Long> triple8 = new Triple<>(1L, 3L, 2L);
Triple<Long, Long, Long> triple9 = new Triple<>(3L, 1L, 2L);
assertEquals(triple, triple);
assertEquals(triple, triple2);
assertNotEquals(triple, triple3);
assertNotEquals(triple, triple4);
assertNotEquals(triple, triple5);
assertNotEquals(triple, triple6);
assertNotEquals(triple, triple7);
assertNotEquals(triple, triple8);
assertNotEquals(triple, triple9);
assertNotEquals(triple, 1L);
}
@Test
public void testHashCode(){
assertEquals(Long.hashCode(1) + Long.hashCode(2) * Long.hashCode(3), triple.hashCode());
}
@Test
public void testToString(){
assertEquals("[1, 2, 3]", triple.toString());
}
}

View File

@@ -1,37 +0,0 @@
//JavaClasses/src/test/java/com/mattrixwv/exceptions/TestInvalidResult.java
//Mattrixwv
// Created: 04-13-23
//Modified: 04-13-23
package com.mattrixwv.exceptions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
public class TestInvalidResult{
private String message = "message";
private Throwable cause = new Exception();
@Test
public void testConstructor(){
InvalidResult exception = new InvalidResult();
assertNull(exception.getMessage());
assertNull(exception.getCause());
exception = new InvalidResult(message);
assertEquals(message, exception.getMessage());
assertNull(exception.getCause());
exception = new InvalidResult(cause);
assertEquals(cause.toString(), exception.getMessage());
assertEquals(cause, exception.getCause());
exception = new InvalidResult(message, cause);
assertEquals(message, exception.getMessage());
assertEquals(cause, exception.getCause());
}
}

View File

@@ -1,83 +0,0 @@
//JavaClasses/src/test/java/com/mattrixwv/generators/TestHexagonalNumberGenerator.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.generators;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestHexagonalNumberGenerator{
private HexagonalNumberGenerator gen;
@BeforeEach
public void setup(){
gen = new HexagonalNumberGenerator();
}
@Test
public void testConstructor(){
gen = new HexagonalNumberGenerator();
assertNotNull(gen);
assertEquals(1L, gen.num);
}
@Test
public void testHasNext(){
assertTrue(gen.hasNext());
gen.num = Long.MAX_VALUE;
assertFalse(gen.hasNext());
}
@Test
public void testNext(){
List<Long> nums = Arrays.asList(1L, 6L, 15L, 28L, 45L, 66L, 91L, 120L, 153L);
ArrayList<Long> generatedNums = new ArrayList<>();
for(int cnt = 0;cnt < nums.size();++cnt){
generatedNums.add(gen.next());
}
assertEquals(nums, generatedNums);
gen.num = Long.MAX_VALUE;
assertThrows(NoSuchElementException.class, () -> {
gen.next();
});
}
@Test
public void testIsHexagonal(){
assertTrue(HexagonalNumberGenerator.isHexagonal(153L));
assertFalse(HexagonalNumberGenerator.isHexagonal(154L));
}
}

View File

@@ -1,83 +0,0 @@
//JavaClasses/src/test/java/com/mattrixwv/generators/TestPentagonalNumberGenerator.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.generators;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestPentagonalNumberGenerator{
private PentagonalNumberGenerator gen;
@BeforeEach
public void setup(){
gen = new PentagonalNumberGenerator();
}
@Test
public void testConstructor(){
assertNotNull(gen);
assertEquals(1L, gen.num);
}
@Test
public void testHasNext(){
assertTrue(gen.hasNext());
gen.num = Long.MAX_VALUE;
assertFalse(gen.hasNext());
}
@Test
public void testNext(){
List<Long> nums = Arrays.asList(1L, 5L, 12L, 22L, 35L, 51L, 70L, 92L, 117L);
ArrayList<Long> generatedNums = new ArrayList<>();
for(int cnt = 0;cnt < nums.size();++cnt){
generatedNums.add(gen.next());
}
assertEquals(nums, generatedNums);
gen.num = Long.MAX_VALUE;
assertThrows(NoSuchElementException.class, () -> {
gen.next();
});
}
@Test
public void testIsPentagonal(){
assertTrue(PentagonalNumberGenerator.isPentagonal(117L));
assertFalse(PentagonalNumberGenerator.isPentagonal(118L));
}
}

View File

@@ -1,77 +0,0 @@
//JavaClasses/src/test/java/mattrixwv/TestSieveOfEratosthenes.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 04-13-23
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
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.generators;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestSieveOfEratosthenes{
private SieveOfEratosthenes sieve;
@BeforeEach
public void setup(){
sieve = new SieveOfEratosthenes();
}
@Test
public void testConstructor(){
assertEquals(2L, sieve.possiblePrime);
assertEquals(new HashMap<>(), sieve.dict);
}
@Test
public void testHasNext(){
assertTrue(sieve.hasNext());
}
@Test
public void testNext(){
List<Long> correctAnswer = Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L);
ArrayList<Long> answer = new ArrayList<>();
for(int cnt = 0;cnt < 25;++cnt){
long prime = sieve.next();
answer.add(prime);
}
assertEquals(correctAnswer, answer);
sieve.possiblePrime = Long.MAX_VALUE;
sieve.dict.put(Long.MAX_VALUE, new ArrayList<>());
sieve.dict.put(Long.MAX_VALUE + 2, new ArrayList<>());
assertThrows(NoSuchElementException.class, () -> {
sieve.next();
});
}
}

View File

@@ -1,69 +0,0 @@
//JavaClasses/src/test/java/mattrixwv/TestSieveOfEratosthenesBig.java
//Matthew Ellison
// Created: 04-13-23
//Modified: 04-13-23
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
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.generators;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestSieveOfEratostheneseBig{
private SieveOfEratosthenesBig sieve;
@BeforeEach
public void setup(){
sieve = new SieveOfEratosthenesBig();
}
@Test
public void testConstructor(){
assertEquals(BigInteger.TWO, sieve.possiblePrime);
assertEquals(new HashMap<>(), sieve.dict);
}
@Test
public void testHasNext(){
assertTrue(sieve.hasNext());
}
@Test
public void testNext(){
List<BigInteger> correctAnswer = Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97));
ArrayList<BigInteger> answer = new ArrayList<>();
for(int cnt = 0;cnt < 25;++cnt){
BigInteger prime = sieve.next();
answer.add(prime);
}
assertEquals(correctAnswer, answer);
}
}

View File

@@ -1,82 +0,0 @@
//JavaClasses/src/test/java/com/mattrixwv/generators/TestTriangularNumberGenerator.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.generators;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestTriangularNumberGenerator{
private TriangularNumberGenerator gen;
@BeforeEach
public void setup(){
gen = new TriangularNumberGenerator();
}
@Test
public void testConstructor(){
gen = new TriangularNumberGenerator();
assertEquals(1L, gen.num);
}
@Test
public void testHasNext(){
assertTrue(gen.hasNext());
gen.num = Long.MAX_VALUE;
assertFalse(gen.hasNext());
}
@Test
public void testNext(){
List<Long> nums = Arrays.asList(1L, 3L, 6L, 10L, 15L, 21L, 28L, 36L, 45L);
ArrayList<Long> generatedNums = new ArrayList<>();
for(int cnt = 0;cnt < nums.size();++cnt){
generatedNums.add(gen.next());
}
assertEquals(nums, generatedNums);
gen.num = Long.MAX_VALUE;
assertThrows(NoSuchElementException.class, () -> {
gen.next();
});
}
@Test
public void testIsTriangular(){
assertTrue(TriangularNumberGenerator.isTriangular(55L));
assertFalse(TriangularNumberGenerator.isTriangular(54L));
}
}

View File

@@ -0,0 +1,114 @@
//JavaClasses/src/test/java/mattrixwv/TestArrayAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 07-03-21
//This class contains tests for my array algorithms
/*
Copyright (C) 2021 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 mattrixwv;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
public class TestArrayAlgorithms{
@Test
public void testGetSum(){
//Test 1
Integer correctAnswer = 0;
ArrayList<Integer> numbers = new ArrayList<Integer>();
Integer answer = ArrayAlgorithms.getSum(numbers);
assertEquals("getSum Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = 118;
numbers = new ArrayList<Integer>(Arrays.asList(2, 2, 3, 3, 4, 4, 100));
answer = ArrayAlgorithms.getSum(numbers);
assertEquals("getSum Integer 2 failed", correctAnswer, answer);
//Test 3
Long longCorrectAnswer = 118L;
ArrayList<Long> longNumbers = new ArrayList<Long>(Arrays.asList(2L, 2L, 3L, 3L, 4L, 4L, 100L));
Long longAnswer = ArrayAlgorithms.getLongSum(longNumbers);
assertEquals("getSum Long failed", longCorrectAnswer, longAnswer);
//Test 4
BigInteger bigCorrectAnswer = BigInteger.valueOf(118);
ArrayList<BigInteger> bigNumbers = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(3), BigInteger.valueOf(4), BigInteger.valueOf(4), BigInteger.valueOf(100)));
BigInteger bigAnswer = ArrayAlgorithms.getBigSum(bigNumbers);
assertEquals("getSum BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetProd(){
//Test 1
Integer correctAnswer = 0;
ArrayList<Integer> numbers = new ArrayList<Integer>();
Integer answer = ArrayAlgorithms.getProd(numbers);
assertEquals("getProd Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = 57600;
numbers = new ArrayList<Integer>(Arrays.asList(2, 2, 3, 3, 4, 4, 100));
answer = ArrayAlgorithms.getProd(numbers);
assertEquals("getProd Integer 2 failed", correctAnswer, answer);
//Test 3
Long longCorrectAnswer = 57600L;
ArrayList<Long> longNumbers = new ArrayList<Long>(Arrays.asList(2L, 2L, 3L, 3L, 4L, 4L, 100L));
Long longAnswer = ArrayAlgorithms.getLongProd(longNumbers);
assertEquals("getProd Long failed", longCorrectAnswer, longAnswer);
//Test 4
BigInteger bigCorrectAnswer = BigInteger.valueOf(57600);
ArrayList<BigInteger> bigNumbers = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(3), BigInteger.valueOf(4), BigInteger.valueOf(4), BigInteger.valueOf(100)));
BigInteger bigAnswer = ArrayAlgorithms.getBigProd(bigNumbers);
assertEquals("getProd BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testPrintList(){
//Test 1
ArrayList<Integer> nums = new ArrayList<Integer>();
String correctAnswer = "[]";
String answer = ArrayAlgorithms.printList(nums);
assertEquals("printList<Integer> 1 failed", correctAnswer, answer);
//Test 2
nums = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
correctAnswer = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]";
answer = ArrayAlgorithms.printList(nums);
assertEquals("printList<Integer> 2 failed", correctAnswer, answer);
//Test 3
nums = new ArrayList<Integer>(Arrays.asList(-3, -2, -1, 0, 1, 2, 3));
correctAnswer = "[-3, -2, -1, 0, 1, 2, 3]";
answer = ArrayAlgorithms.printList(nums);
assertEquals("printList<Integer> 3 failed", correctAnswer, answer);
//Test 4
ArrayList<String> strings = new ArrayList<String>(Arrays.asList("A", "B", "C"));
correctAnswer = "[A, B, C]";
answer = ArrayAlgorithms.printList(strings);
assertEquals("printList<String> 1 failed", correctAnswer, answer);
//Test 5
strings = new ArrayList<String>(Arrays.asList("abc", "def", "ghi"));
correctAnswer = "[abc, def, ghi]";
answer = ArrayAlgorithms.printList(strings);
assertEquals("printList<String> 2 failed", correctAnswer, answer);
}
}

View File

@@ -0,0 +1,399 @@
//JavaClasses/src/test/java/mattrixwv/TestNumberAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 07-03-21
//This class contains tests for my number algorithms
/*
Copyright (C) 2021 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 mattrixwv;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
import mattrixwv.exceptions.InvalidResult;
public class TestNumberAlgorithms{
@Test
public void testGetPrimes(){
//Test 1
ArrayList<Integer> correctAnswer = new ArrayList<Integer>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97));
Integer topNum = 100;
ArrayList<Integer> answer = NumberAlgorithms.getPrimes(topNum);
assertEquals("getPrimes Integer failed", correctAnswer, answer);
//Test 2
ArrayList<Long> longCorrectAnswer = new ArrayList<Long>(Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L));
Long longTopNum = 100L;
ArrayList<Long> longAnswer = NumberAlgorithms.getPrimes(longTopNum);
assertEquals("getPrimes Long failed", longCorrectAnswer, longAnswer);
//Test 3
ArrayList<BigInteger> bigCorrectAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97)));
BigInteger bigTopNum = BigInteger.valueOf(100);
ArrayList<BigInteger> bigAnswer = NumberAlgorithms.getPrimes(bigTopNum);
assertEquals("getPrimes BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetNumPrimes(){
//Test 1
ArrayList<Integer> correctAnswer = new ArrayList<Integer>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97));
Integer numPrimes = 25;
ArrayList<Integer> answer = NumberAlgorithms.getNumPrimes(numPrimes);
assertEquals("getNumPrimes Integer failed", correctAnswer, answer);
//Test 2
ArrayList<Long> longCorrectAnswer = new ArrayList<Long>(Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L));
Long longNumPrimes = 25L;
ArrayList<Long> longAnswer = NumberAlgorithms.getNumPrimes(longNumPrimes);
assertEquals("getNumPrimes Long failed", longCorrectAnswer, longAnswer);
//Test 3
ArrayList<BigInteger> bigCorrectAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97)));
BigInteger bigNumPrimes = BigInteger.valueOf(25);
ArrayList<BigInteger> bigAnswer = NumberAlgorithms.getNumPrimes(bigNumPrimes);
assertEquals("getNumPrimes BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testIsPrime(){
//Test 1
int num = 2;
boolean correctAnswer = true;
boolean answer = NumberAlgorithms.isPrime(num);
assertEquals("isPrime Integer 1 failed", correctAnswer, answer);
//Test 2
num = 97;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(num);
assertEquals("isPrime Integer 2 failed", correctAnswer, answer);
//Test 3
num = 1000;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals("isPrime Integer 3 failed", correctAnswer, answer);
//Test 4
num = 1;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(num);
assertEquals("isPrime Integer 4 failed", correctAnswer, answer);
//Test 5
long longNum = 2;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals("isPrime Long 1 failed", correctAnswer, answer);
//Test 6
longNum = 97;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals("isPrime Long 2 failed", correctAnswer, answer);
//Test 7
longNum = 1000;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals("isPrime Long 3 failed", correctAnswer, answer);
//Test 8
longNum = 1;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(longNum);
assertEquals("isPrime Long 4 failed", correctAnswer, answer);
//Test 9
BigInteger bigNum = BigInteger.TWO;
correctAnswer = true;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals("isPrime BigInteger 1 failed", correctAnswer, answer);
//Test 10
bigNum = BigInteger.valueOf(97);
correctAnswer = true;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals("isPrime BigInteger 2 failed", correctAnswer, answer);
//Test 11
bigNum = BigInteger.valueOf(1000);
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals("isPrime BigInteger 3 failed", correctAnswer, answer);
//Test 12
bigNum = BigInteger.ONE;
correctAnswer = false;
answer = NumberAlgorithms.isPrime(bigNum);
assertEquals("isPrime BigInteger 4 failed", correctAnswer, answer);
}
@Test
public void testGetFactors() throws InvalidResult{
//Test 1
ArrayList<Integer> correctAnswer = new ArrayList<Integer>(Arrays.asList(2, 2, 5, 5));
Integer number = 100;
ArrayList<Integer> answer = NumberAlgorithms.getFactors(number);
assertEquals("getFactors Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = new ArrayList<Integer>(Arrays.asList(2, 7, 7));
number = 98;
answer = NumberAlgorithms.getFactors(number);
assertEquals("getFactors Integer 2 failed", correctAnswer, answer);
//Test 3
ArrayList<Long> longCorrectAnswer = new ArrayList<Long>(Arrays.asList(2L, 2L, 5L, 5L));
Long longNumber = 100L;
ArrayList<Long> longAnswer = NumberAlgorithms.getFactors(longNumber);
assertEquals("getFactors Long failed", longCorrectAnswer, longAnswer);
//Test 4
ArrayList<BigInteger> bigCorrectAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(7), BigInteger.valueOf(7)));
BigInteger bigNumber = BigInteger.valueOf(98);
ArrayList<BigInteger> bigAnswer = NumberAlgorithms.getFactors(bigNumber);
assertEquals("getFactors BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetDivisors(){
//Test 1
ArrayList<Integer> correctAnswer = new ArrayList<Integer>(Arrays.asList(1, 2, 4, 5, 10, 20, 25, 50, 100));
Integer topNum = 100;
ArrayList<Integer> answer = NumberAlgorithms.getDivisors(topNum);
assertEquals("getDivisors Integer failed", correctAnswer, answer);
//Test 2
ArrayList<Long> longCorrectAnswer = new ArrayList<Long>(Arrays.asList(1L, 2L, 4L, 5L, 10L, 20L, 25L, 50L, 100L));
Long longTopNum = 100L;
ArrayList<Long> longAnswer = NumberAlgorithms.getDivisors(longTopNum);
assertEquals("getDivisors Long failed", longCorrectAnswer, longAnswer);
//Test 3
ArrayList<BigInteger> bigCorrectAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(2), BigInteger.valueOf(4), BigInteger.valueOf(5), BigInteger.valueOf(10), BigInteger.valueOf(20), BigInteger.valueOf(25), BigInteger.valueOf(50), BigInteger.valueOf(100)));
BigInteger bigTopNum = BigInteger.valueOf(100);
ArrayList<BigInteger> bigAnswer = NumberAlgorithms.getDivisors(bigTopNum);
assertEquals("getDivisors BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetFib(){
//Test 1
Integer correctAnswer = 144;
Integer number = 12;
Integer answer = NumberAlgorithms.getFib(number);
assertEquals("getFib Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = 6765;
number = 20;
answer = NumberAlgorithms.getFib(number);
assertEquals("getFib Integer 2 failed", correctAnswer, answer);
//Test 3
Long longCorrectAnswer = 6765L;
Long longNumber = 20L;
Long longAnswer = NumberAlgorithms.getFib(longNumber);
assertEquals("getFib Long failed", longCorrectAnswer, longAnswer);
//Test 4
BigInteger bigCorrectAnswer = new BigInteger("1070066266382758936764980584457396885083683896632151665013235203375314520604694040621889147582489792657804694888177591957484336466672569959512996030461262748092482186144069433051234774442750273781753087579391666192149259186759553966422837148943113074699503439547001985432609723067290192870526447243726117715821825548491120525013201478612965931381792235559657452039506137551467837543229119602129934048260706175397706847068202895486902666185435124521900369480641357447470911707619766945691070098024393439617474103736912503231365532164773697023167755051595173518460579954919410967778373229665796581646513903488154256310184224190259846088000110186255550245493937113651657039447629584714548523425950428582425306083544435428212611008992863795048006894330309773217834864543113205765659868456288616808718693835297350643986297640660000723562917905207051164077614812491885830945940566688339109350944456576357666151619317753792891661581327159616877487983821820492520348473874384736771934512787029218636250627816");
BigInteger bigNumber = BigInteger.valueOf(4782);
BigInteger bigAnswer = NumberAlgorithms.getFib(bigNumber);
assertEquals("getFib BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testGetAllFib(){
//Test 1
ArrayList<Integer> correctAnswer = new ArrayList<Integer>(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89));
Integer highestNumber = 100;
ArrayList<Integer> answer = NumberAlgorithms.getAllFib(highestNumber);
assertEquals("getAllFib Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = new ArrayList<Integer>(Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987));
highestNumber = 1000;
answer = NumberAlgorithms.getAllFib(highestNumber);
assertEquals("getAllFib Integer 2 failed", correctAnswer, answer);
//Test 3
ArrayList<Long> longCorrectAnswer = new ArrayList<Long>(Arrays.asList(1L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L));
Long longHighestNumber = 1000L;
ArrayList<Long> longAnswer = NumberAlgorithms.getAllFib(longHighestNumber);
assertEquals("getAllFib Long failed", longCorrectAnswer, longAnswer);
//Test 4
ArrayList<BigInteger> bigCorrectAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(8), BigInteger.valueOf(13), BigInteger.valueOf(21), BigInteger.valueOf(34), BigInteger.valueOf(55), BigInteger.valueOf(89)));
BigInteger bigHighestNumber = BigInteger.valueOf(100);
ArrayList<BigInteger> bigAnswer = NumberAlgorithms.getAllFib(bigHighestNumber);
assertEquals("getAllFib BigInteger failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testFactorial(){
//Integer
//Test 1
Integer correctAnswer = 720;
Integer number = 6;
Integer answer = NumberAlgorithms.factorial(number);
assertEquals("factorial Integer 1 failed", correctAnswer, answer);
//Test 2
correctAnswer = 479001600;
number = 12;
answer = NumberAlgorithms.factorial(number);
assertEquals("factorial Integer 2 failed", correctAnswer, answer);
//Long
//Test 3
Long correctAnswerLong = 720L;
Long numberLong = 6L;
Long answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals("factorial Long 1 failed", correctAnswerLong, answerLong);
//Test 4
correctAnswerLong = 479001600L;
numberLong = 12L;
answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals("factorial Long 2 failed", correctAnswerLong, answerLong);
//Test 5
correctAnswerLong = 2432902008176640000L;
numberLong = 20L;
answerLong = NumberAlgorithms.factorial(numberLong);
assertEquals("factorial Long 3 failed", correctAnswerLong, answerLong);
//BigInteger
//Test 6
BigInteger correctAnswerBig = BigInteger.valueOf(720L);
BigInteger numberBig = BigInteger.valueOf(6);
BigInteger answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals("factorial BigInteger 1 failed", correctAnswerBig, answerBig);
//Test 7
correctAnswerBig = BigInteger.valueOf(479001600L);
numberBig = BigInteger.valueOf(12);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals("factorial BigInteger 2 failed", correctAnswerBig, answerBig);
//Test 8
correctAnswerBig = BigInteger.valueOf(2432902008176640000L);
numberBig = BigInteger.valueOf(20L);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals("factorial BigInteger 3 failed", correctAnswerBig, answerBig);
//Test 9
correctAnswerBig = new BigInteger("265252859812191058636308480000000");
numberBig = BigInteger.valueOf(30L);
answerBig = NumberAlgorithms.factorial(numberBig);
assertEquals("factorial BigInteger 4 failed", correctAnswerBig, answerBig);
}
@Test
public void testGCD(){
//Test 1
int num1 = 2;
int num2 = 3;
int correctAnswer = 1;
int answer = NumberAlgorithms.gcd(num1, num2);
assertEquals("GCD Integer 1 failed", correctAnswer, answer);
//Test 2
num1 = 1000;
num2 = 575;
correctAnswer = 25;
answer = NumberAlgorithms.gcd(num1, num2);
assertEquals("GCD Integer 2 failed", correctAnswer, answer);
//Test 3
num1 = 1000;
num2 = 1000;
correctAnswer = 1000;
answer = NumberAlgorithms.gcd(num1, num2);
assertEquals("GCD Integer 3 failed", correctAnswer, answer);
//Test 4
long longNum1 = 2;
long longNum2 = 3;
long longCorrectAnswer = 1;
long longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals("GCD Long 1 failed", longCorrectAnswer, longAnswer);
//Test 5
longNum1 = 1000;
longNum2 = 575;
longCorrectAnswer = 25;
longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals("GCD Long 2 failed", longCorrectAnswer, longAnswer);
//Test 6
longNum1 = 1000;
longNum2 = 1000;
longCorrectAnswer = 1000;
longAnswer = NumberAlgorithms.gcd(longNum1, longNum2);
assertEquals("GCD Long 3 failed", longCorrectAnswer, longAnswer);
//Test 7
BigInteger bigNum1 = BigInteger.TWO;
BigInteger bigNum2 = BigInteger.valueOf(3);
BigInteger bigCorrectAnswer = BigInteger.ONE;
BigInteger bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals("GCD BigInteger 1 failed", bigCorrectAnswer, bigAnswer);
//Test 8
bigNum1 = BigInteger.valueOf(1000);
bigNum2 = BigInteger.valueOf(575);
bigCorrectAnswer = BigInteger.valueOf(25);
bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals("GCD BigInteger 2 failed", bigCorrectAnswer, bigAnswer);
//Test 9
bigNum1 = BigInteger.valueOf(1000);
bigNum2 = BigInteger.valueOf(1000);
bigCorrectAnswer = BigInteger.valueOf(1000);
bigAnswer = NumberAlgorithms.gcd(bigNum1, bigNum2);
assertEquals("GCD BigInteger 3 failed", bigCorrectAnswer, bigAnswer);
}
@Test
public void testToBin(){
//Test 1
int num = 7;
String correctAnswer = "111";
String answer = NumberAlgorithms.toBin(num);
assertEquals("toBin 1 failed", correctAnswer, answer);
//Test 2
num = 0;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(num);
assertEquals("toBin 2 failed", correctAnswer, answer);
//Test 3
num = 1000000;
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(num);
assertEquals("toBin 3 failed", correctAnswer, answer);
//Test 4
long longNum = 7;
correctAnswer = "111";
answer = NumberAlgorithms.toBin(longNum);
assertEquals("toBin long 1 failed", correctAnswer, answer);
//Test 5
longNum = 0;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(longNum);
assertEquals("toBin long 2 failed", correctAnswer, answer);
//Test 6
longNum = 1000000;
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(longNum);
assertEquals("toBin long 3 failed", correctAnswer, answer);
//Test 7
BigInteger bigNum = BigInteger.valueOf(7);
correctAnswer = "111";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals("toBin big 1 failed", correctAnswer, answer);
//Test 8
bigNum = BigInteger.ZERO;
correctAnswer = "0";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals("toBin big 2 failed", correctAnswer, answer);
//Test 9
bigNum = BigInteger.valueOf(1000000);
correctAnswer = "11110100001001000000";
answer = NumberAlgorithms.toBin(bigNum);
assertEquals("toBin big 3 failed", correctAnswer, answer);
}
}

View File

@@ -0,0 +1,59 @@
//JavaClasses/src/test/java/mattrixwv/TestSieveOfEratosthenes.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 06-30-21
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2021 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 mattrixwv;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
public class TestSieveOfEratosthenes{
@Test
public void testSieveOfEratosthenes(){
//Test 1
SieveOfEratosthenes sieve = new SieveOfEratosthenes();
ArrayList<Long> correctAnswer = new ArrayList<Long>(Arrays.asList(2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L, 29L, 31L, 37L, 41L, 43L, 47L, 53L, 59L, 61L, 67L, 71L, 73L, 79L, 83L, 89L, 97L));
ArrayList<Long> answer = new ArrayList<Long>();
for(int cnt = 0;cnt < 25;++cnt){
long prime = sieve.next();
answer.add(prime);
}
assertEquals("SieveOfEratosthenes failed", correctAnswer, answer);
}
@Test
public void testSieveOfEratosthenesBig(){
//Test 1
SieveOfEratosthenesBig sieve = new SieveOfEratosthenesBig();
ArrayList<BigInteger> correctAnswer = new ArrayList<BigInteger>(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(3), BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(11), BigInteger.valueOf(13), BigInteger.valueOf(17), BigInteger.valueOf(19), BigInteger.valueOf(23), BigInteger.valueOf(29), BigInteger.valueOf(31), BigInteger.valueOf(37), BigInteger.valueOf(41), BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), BigInteger.valueOf(59), BigInteger.valueOf(61), BigInteger.valueOf(67), BigInteger.valueOf(71), BigInteger.valueOf(73), BigInteger.valueOf(79), BigInteger.valueOf(83), BigInteger.valueOf(89), BigInteger.valueOf(97)));
ArrayList<BigInteger> answer = new ArrayList<BigInteger>();
for(int cnt = 0;cnt < 25;++cnt){
BigInteger prime = sieve.next();
answer.add(prime);
}
assertEquals("SieveOfEratosthenesBig failed", correctAnswer, answer);
}
}

View File

@@ -1,11 +1,11 @@
//JavaClasses/src/test/java/mattrixwv/TestStopwatch.java //JavaClasses/src/test/java/mattrixwv/TestStopwatch.java
//Matthew Ellison //Matthew Ellison
// Created: 06-07-20 // Created: 06-07-20
//Modified: 04-13-23 //Modified: 07-28-20
//This class holds many algorithms that I have found it useful to keep around //This class holds many algorithms that I have found it useful to keep around
//As such all of the functions in here are static and meant to be used as stand alone functions //As such all of the functions in here are static and meant to be used as stand alone functions
/* /*
Copyright (C) 2023 Matthew Ellison Copyright (C) 2020 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,32 +22,25 @@ Copyright (C) 2023 Matthew Ellison
*/ */
package com.mattrixwv; package mattrixwv;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
import com.mattrixwv.exceptions.InvalidResult;
import mattrixwv.exceptions.InvalidResult;
public class TestStopwatch{ public class TestStopwatch{
private static final Integer NUM_TO_RUN = 100000; private static final Integer NUM_TO_RUN = 100000;
private static final Double ALLOWANCE = .0000000001; private static final Double ALLOWANCE = .0000000001;
@Test @Test
public void testStartStop(){ public void testStartStop(){
Stopwatch timer = new Stopwatch(); Stopwatch timer = new Stopwatch();
timer.start(); timer.start();
timer.stop(); timer.stop();
assertNotNull(timer.toString());
//If it gets to here without throwing an exception everything went well //If it gets to here without throwing an exception everything went well
} }
@Test @Test
public void testConversion() throws InvalidResult{ public void testConversion() throws InvalidResult{
Stopwatch timer = new Stopwatch(); Stopwatch timer = new Stopwatch();
@@ -61,16 +54,15 @@ public class TestStopwatch{
//Stop the timer //Stop the timer
timer.stop(); timer.stop();
//Assert something so the sum isn't ignored during compile //Assert something so the sum isn't ignored during compile
assertNotEquals(sum, Integer.valueOf(0), "You really messed up"); assertNotEquals("You really messed up", sum, Integer.valueOf(0));
//Check that the different resolutions work out correctly //Check that the different resolutions work out correctly
Double nano = timer.getNano(); Double nano = timer.getNano();
assertEquals(timer.getMicro(), (nano / 1000D), ALLOWANCE, "Micro resolution test failed"); assertEquals("Micro resolution test failed", timer.getMicro(), (nano / 1000D), ALLOWANCE);
assertEquals(timer.getMilli(), (nano / 1000000D), ALLOWANCE, "Milli resolution test failed"); assertEquals("Milli resolution test failed", timer.getMilli(), (nano / 1000000D), ALLOWANCE);
assertEquals(timer.getSecond(), (nano / 1000000000D), ALLOWANCE, "Second resolution test failed"); assertEquals("Second resolution test failed", timer.getSecond(), (nano / 1000000000D), ALLOWANCE);
assertEquals(timer.getMinute(), (nano / 60000000000D), ALLOWANCE, "Minute resolution test failed"); assertEquals("Minute resolution test failed", timer.getMinute(), (nano / 60000000000D), ALLOWANCE);
assertEquals(timer.getHour(), (nano / 3600000000000D), ALLOWANCE, "Hour resolution test failed"); assertEquals("Hour resolution test failed", timer.getHour(), (nano / 3600000000000D), ALLOWANCE);
} }
@Test @Test
public void testStringConversion() throws InvalidResult{ public void testStringConversion() throws InvalidResult{
//Test nanoseconds //Test nanoseconds
@@ -82,8 +74,6 @@ public class TestStopwatch{
//Test milliseconds //Test milliseconds
results = Stopwatch.getStr(1.0e6); results = Stopwatch.getStr(1.0e6);
assertEquals("1.000 milliseconds", results); assertEquals("1.000 milliseconds", results);
results = Stopwatch.getStr(1.2e8);
assertEquals("120.000 milliseconds", results);
//Test seconds //Test seconds
results = Stopwatch.getStr(1.0e9); results = Stopwatch.getStr(1.0e9);
assertEquals("1.000 seconds", results); assertEquals("1.000 seconds", results);
@@ -93,25 +83,5 @@ public class TestStopwatch{
//Test hours //Test hours
results = Stopwatch.getStr(1.0e13); results = Stopwatch.getStr(1.0e13);
assertEquals("2.778 hours", results); assertEquals("2.778 hours", results);
//Test error
assertThrows(InvalidResult.class, () -> {
Stopwatch.getStr(-1.0);
});
}
@Test
public void testErrors(){
Stopwatch timer = new Stopwatch();
assertEquals(0.0, timer.getNano(), "Stopwatch failed not started test");
timer.stop();
assertEquals(0.0, timer.getNano(), "Stopwatch failed stop before start test");
timer.start();
assertNotEquals(0.0, timer.getNano(), "Stopwatch failed not stopped test");
timer.reset();
assertEquals(0.0, timer.getNano(), "Stopwatch failed reset test");
} }
} }

View File

@@ -0,0 +1,79 @@
//JavaClasses/src/test/java/mattrixwv/TestStringAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 07-03-21
//This class contains tests for my number algorithms
/*
Copyright (C) 2021 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 mattrixwv;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
public class TestStringAlgorithms{
@Test
public void testGetPermutations(){
//Test 1
String permString = "012";
ArrayList<String> correctAnswer = new ArrayList<String>(Arrays.asList("012", "021", "102", "120", "201", "210"));
ArrayList<String> answer = StringAlgorithms.getPermutations(permString);
assertEquals("getPermutations failed", correctAnswer, answer);
}
@Test
public void testFindNumOccurrence(){
//Test 1
String testString = "abcdefgdd";
char testChar = 'a';
long correctAnswer = 1;
long answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals("FindNumOccurrence 1 failed", correctAnswer, answer);
//Test 2
testChar = 'd';
correctAnswer = 3;
answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals("FindNumOccurrence 2 failed", correctAnswer, answer);
//Test 3
testChar = 'h';
correctAnswer = 0;
answer = StringAlgorithms.findNumOccurrence(testString, testChar);
assertEquals("FindNumOccurrence 3 failed", correctAnswer, answer);
}
@Test
public void testIsPalindrome(){
//Test 1
String str = "101";
boolean correctAnswer = true;
boolean answer = StringAlgorithms.isPalindrome(str);
assertEquals("isPalindrome 1 failed", correctAnswer, answer);
//Test 2
str = "100";
correctAnswer = false;
answer = StringAlgorithms.isPalindrome(str);
assertEquals("isPalindrome 2 failed", correctAnswer, answer);
//Test 3
str = "";
correctAnswer = true;
answer = StringAlgorithms.isPalindrome(str);
assertEquals("isPalindrome 3 failed", correctAnswer, answer);
}
}

View File

@@ -0,0 +1 @@
Create test for isPrime

View File

@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" comparisonMethod="maven"
xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 https://www.mojohaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd">
<ignoreVersions>
<!-- Ignore Alpha's, Beta's, release candidates and milestones -->
<ignoreVersion type="regex">(?i).*Alpha(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*a(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*Beta(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*-B(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*RC(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*CR(?:-?\d+)?</ignoreVersion>
<ignoreVersion type="regex">(?i).*M(?:-?\d+)?</ignoreVersion>
</ignoreVersions>
<rules>
</rules>
</ruleset>