//typescriptClasses/Algorithms.ts //Matthew Ellison // Created: 10-19-20 //Modified: 03-10-21 //This class holds many algorithms that I have 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 . */ import { InvalidResult } from "./InvalidResult"; export function arrayEquals(array1: any[], array2: any[]): boolean{ //If they aren't the same type they aren't equal if((typeof array1) != (typeof array2)){ return false; } //If they aren't the same length they aren't equal else if(array1.length != array2.length){ return false; } else{ //Loop through every element to see if each one is equal for(let cnt = 0;cnt < array1.length;++cnt){ //If any element in the same location is different return false if(array1[cnt] != array2[cnt]){ return false; } } //If every element was the same they are equal return true; } } export function sqrtBig(value: bigint): bigint{ if(value < 0n){ throw "Negative numbers are not supported"; } let k = 2n; let o = 0n; let x = value; let limit = 100; while(x ** k !== k && x !== o && --limit){ o = x; x = ((k - 1n) * x + value / x ** (k - 1n)) / k; } return x; } export function getAllFib(goalNumber: number): number[]{ //Setup the variables let fibNums: number[] = []; //If the number is <= 0 return an empty list if(goalNumber <= 0){ return fibNums; } else if(goalNumber == 1){ fibNums.push(1); return fibNums; } //This means that at least 2 1's are elements fibNums.push(1); fibNums.push(1); //Loop to generate the rest of the Fibonacci numbers while(fibNums[fibNums.length - 1] <= goalNumber){ fibNums.push((fibNums[fibNums.length - 1]) + (fibNums[fibNums.length - 2])); } //At this point the most recent number is > goalNumber, so remove it and return the rest of the list fibNums.pop(); return fibNums; } export function getAllFibBig(goalNumber: bigint): bigint[]{ //Setup the variables let fibNums:bigint[] = []; //If the number is <= 0 return an empty list if(goalNumber <= 0){ return fibNums; } else if(goalNumber == 1n){ fibNums.push(1n); return fibNums; } //This means that at least 2 1's are elements fibNums.push(1n); fibNums.push(1n); //Loop to generate the rest of the Fibonacci numbers while(fibNums[fibNums.length - 1] <= goalNumber){ fibNums.push((fibNums[fibNums.length - 1]) + (fibNums[fibNums.length - 2])); } //At this point the most recent number is > goalNumber, so remove it and return the rest of the list fibNums.pop(); return fibNums; } export function getPrimes(goalNumber: number): number[]{ let primes: number[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or a negative return an empty list if(goalNumber <= 1){ return primes; } //Optherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2); } //We can now start at 3 and skip all even numbers, because they cannot be prime for(let possiblePrime: number = 3;possiblePrime <= goalNumber;possiblePrime += 2){ //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: number = 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(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of range if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort((n1, n2) => n1 - n2); return primes; } export function getPrimesBig(goalNumber: bigint): bigint[]{ let primes: bigint[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or a negative return an empty list if(goalNumber <= 1){ return primes; } //Optherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2n); } //We can now start at 3 and skip all even numbers, because they cannot be prime for(let possiblePrime: bigint = 3n;possiblePrime <= goalNumber;possiblePrime += 2n){ //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: bigint = sqrtBig(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(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0n){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of range if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort(function(n1, n2){ if(n1 > n2){ return 1; } else if(n1 < n2){ return -1; } else{ return 0; } }); return primes; } export function getNumPrimes(numberOfPrimes: number): number[]{ let primes: number[] = []; //Holds the prime numbers let foundFactor: boolean = 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; } //Otherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2); } //We can now start at 3 and skip all even number, because they cannot be prime for(let possiblePrime: number = 3;primes.length < numberOfPrimes;possiblePrime += 2){ //Check all the current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: number = 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 by default for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of bounds if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort((n1, n2) => n1 - n2); return primes; } export function getNumPrimesBig(numberOfPrimes: bigint): bigint[]{ let primes: bigint[] = []; //Holds the prime numbers let foundFactor: boolean = 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; } //Otherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2n); } //We can now start at 3 and skip all even number, because theyu cannot be prime for(let possiblePrime: bigint = 3n;primes.length < numberOfPrimes;possiblePrime += 2n){ //Check all the current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: bigint = sqrtBig(possiblePrime); //We can safely assume that ther ewill be at least 1 element in the primes list because of 2 being added by default for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0n){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of bounds if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort(function(n1, n2){ if(n1 > n2){ return 1; } else if(n1 < n2){ return -1; } else{ return 0; } }); return primes; } export function isPrime(possiblePrime: number): boolean{ if(possiblePrime <= 3){ return possiblePrime > 1; } else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){ return false; } for(let cnt: number = 5;(cnt * cnt) <= possiblePrime; cnt += 6){ if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){ return false; } } return true; } export function isPrimeBig(possiblePrime: bigint): boolean{ if(possiblePrime <= 3n){ return possiblePrime > 1n; } else if(((possiblePrime % 2n) == 0n) || ((possiblePrime % 3n) == 0n)){ return false; } for(let cnt : bigint = 5n;(cnt * cnt) <= possiblePrime;cnt += 6n){ if(((possiblePrime % cnt) == 0n) || ((possiblePrime % (cnt + 2n)) == 0n)){ return false; } } return true; } export function getFactors(goalNumber: number): number[]{ //You need to get all the primes that could be factors of this number so you can test them let topPossiblePrime: number = Math.ceil(Math.sqrt(goalNumber)); let primes: number[] = getPrimes(topPossiblePrime); let factors: number[] = []; //You need to step through each prime and see if it is a factor in the number for(let cnt: number = 0;cnt < primes.length;){ //If the prime is a factor you need to add it to the factor list if((goalNumber % primes[cnt]) == 0){ factors.push(primes[cnt]); goalNumber /= primes[cnt]; } //Otherwise advance the location in primes you are looking at //By not advancing f 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.length == 0){ factors.push(goalNumber); goalNumber /= goalNumber; } //If for some reason the goalNumber is not 1 throw an exception if(goalNumber != 1){ throw new InvalidResult("The factor was not 1: " + goalNumber); } //Return the list of factors return factors; } export function getFactorsBig(goalNumber: bigint): bigint[]{ //You need to get all the primes that could be factors of this number so you can test them let topPossiblePrime: bigint = sqrtBig(goalNumber); let primes: bigint[] = getPrimesBig(topPossiblePrime); let factors: bigint[] = []; //You need to step through each prime and see if it is a factor in the number for(let cnt: number = 0;cnt < primes.length;){ //If the prime is a factor you need to add it to the factor list if((goalNumber % primes[cnt]) == 0n){ factors.push(primes[cnt]); goalNumber /= primes[cnt]; } //Otherwise advance the location in primes you are looking at //By not advancing f 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.length == 0){ factors.push(goalNumber); goalNumber /= goalNumber; } //If for some reason the goalNumber is not 1 throw an exception if(goalNumber != 1n){ throw new InvalidResult("The factor was not 1: " + goalNumber); } //Return the list of factors return factors; } export function getDivisors(goalNumber: number): number[]{ let divisors: number[] = []; //Start by checking that the number is positive if(goalNumber <= 0){ return divisors; } //If the number is 1 return just itself else if(goalNumber == 1){ divisors.push(1); return divisors; } //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly let topPossibleDivisor: number = Math.ceil(Math.sqrt(goalNumber)); for(let possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){ //If you find one add it and the number it creates to the list if((goalNumber % possibleDivisor) == 0){ divisors.push(possibleDivisor); //Account for the possibility of sqrt(goalNumber) being a divisor if(possibleDivisor != topPossibleDivisor){ divisors.push(goalNumber / possibleDivisor); } if(divisors[divisors.length - 1] == (possibleDivisor + 1)){ ++possibleDivisor; } } } //Sort the list before returning it for neatness divisors.sort((a, b) => a - b); //Return the list return divisors; } export function getDivisorsBig(goalNumber: bigint): bigint[]{ let divisors: bigint[] = []; //Start by checking that the number is positive if(goalNumber <= 0n){ return divisors; } //If the number is 1 return just itself else if(goalNumber == 1n){ divisors.push(1n); return divisors; } //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly let topPossibleDivisor: bigint = sqrtBig(goalNumber); for(let possibleDivisor = 1n;possibleDivisor <= topPossibleDivisor;++possibleDivisor){ //If you find one add it and the number it creates to the list if((goalNumber % possibleDivisor) == 0n){ divisors.push(possibleDivisor); //Account for the possibility of sqrt(goalNumber) being a divisors if(possibleDivisor != topPossibleDivisor){ divisors.push(goalNumber / possibleDivisor); } if(divisors[divisors.length - 1] == (possibleDivisor + 1n)){ ++possibleDivisor; } } } //Sort the list before returning it for neatness divisors.sort((a, b) => { if(a > b){ return 1; } else if(a < b){ return -1; } else{ return 0; } }); //Return the list return divisors; } export function getSum(ary: number[]): number{ let sum: number = 0; ary.forEach(a => sum += a); return sum; } export function getSumBig(ary: bigint[]): bigint{ let sum: bigint = 0n; ary.forEach(a => sum += a); return sum; } export function getProd(ary: number[]): number{ //Return 0 if the array is empty if(ary.length == 0){ return 0; } let prod: number = 1; ary.forEach(a => prod *= a); return prod; } export function getProdBig(ary: bigint[]): bigint{ //Return 0 if the array is empty if(ary.length == 0){ return 0n; } let prod: bigint = 1n; ary.forEach(a => prod *= a); return prod; } export function getFib(goalSubscript: number): number{ //Setup the variables let fibNums: number[] = [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 let fibLoc: number = 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]; } export function getFibBig(goalSubscript: bigint): bigint{ //Setup the varibles let fibNums: bigint[] = [1n, 1n, 0n]; //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 <= 0n){ return 0n; } //Loop through the list, generating Fibonacci numbers until it finds the correct subscript let fibLoc: bigint = 2n; for(fibLoc = 2n;fibLoc < goalSubscript;++fibLoc){ fibNums[Number(fibLoc % 3n)] = fibNums[Number((fibLoc - 1n) % 3n)] + fibNums[Number((fibLoc - 2n) % 3n)]; } //Return the proper number. The location counter is 1 off of the subscript return fibNums[Number((fibLoc - 1n) % 3n)]; } //This is a function that creates all permutations of a string and returns a vector of those permutations export function getPermutations(master: string): string[]{ return getPermutationsHelper(master, 0); } function getPermutationsHelper(master: string, num: number): string[]{ let perms: string[] = []; //Check if the number is out of bounds if((num >= master.length) || (num < 0)){ //Do nothing and return an empty array } //If this is the last possible recurse just return the current string else if(num == (master.length - 1)){ perms.push(master); } //If there are more possible recurses, recurse with the current permutation else{ let temp: string[] = getPermutationsHelper(master, num + 1); temp.forEach(str => perms.push(str)); //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(let cnt = 1;(num + cnt) < master.length;++cnt){ master = swapString(master, num, (num + cnt)); temp = getPermutationsHelper(master, num + 1); temp.forEach(str => perms.push(str)); master = swapString(master, num, (num + cnt)); } //The array is not necessarily in alph-numeric order. So if this is the full array sort it before returning if(num == 0){ perms.sort(); } } //Return the array that was build return perms; } function swapString(str: string, first: number, second: number): string{ let tempStr: string = str.substr(0, first) + str[second] + str.substr(first + 1, second - first - 1) + str[first] + str.substr(second + 1); return tempStr; } //This function returns the number of times the character occurs in the string export function findNumOccurrence(str: string, ch: string){ let num: number = 0; //Set the number of occurrences to 0 to start //Loop through every character in the string and compare it to the character passed in for(let strCh of str){ //If the character is the same as the one passed in increment the counter if(strCh == ch){ ++num; } } //Return the number of times the character appeared in the string return num; }