diff --git a/src/easy/AdditivePersistence.java b/src/easy/AdditivePersistence.java new file mode 100644 index 0000000..46016b7 --- /dev/null +++ b/src/easy/AdditivePersistence.java @@ -0,0 +1,48 @@ +package easy; + +/** + * Have the function AdditivePersistence(num) take the num parameter being passed + * which will always be a positive integer + * and return its additive persistence which is the number of times + * you must add the digits in num until you reach a single digit. + * --- + * For example: if num is 2718 then your program + * should return 2 because 2 + 7 + 1 + 8 = 18 + * and 1 + 8 = 9, and you stop at 9. + */ +public class AdditivePersistence { + + /** + * Additive Persistence function. + * + * @param num input number + * @return additive persistence which is the number of times + */ + private static int additivePersistence(int num) { + int times = 0; + int added = num; + while (added > 9) { + int sum = 0; + String[] intArr = Integer.toString(added).split(""); + for (String i : intArr) { + sum += Integer.parseInt(i); + } + added = sum; + times++; + } + return times; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = additivePersistence(199); + System.out.println(result1); + var result2 = additivePersistence(913); + System.out.println(result2); + } + +} diff --git a/src/easy/AlphabetSoup.java b/src/easy/AlphabetSoup.java new file mode 100644 index 0000000..a6c679a --- /dev/null +++ b/src/easy/AlphabetSoup.java @@ -0,0 +1,36 @@ +package easy; + +import java.util.Arrays; + +/** + * Have the function AlphabetSoup(str) take the str string parameter being passed + * and return the string with the letters in alphabetical order (i.e. hello becomes ehllo). + * Assume numbers and punctuation symbols will not be included in the string. + */ +public class AlphabetSoup { + + /** + * Alphabet Soup function. + * + * @param str input string + * @return the string with the letters in alphabetical order + */ + private static String alphabetSoup(String str) { + char[] letters = str.toCharArray(); + Arrays.sort(letters); + return String.valueOf(letters); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = alphabetSoup("leftfield"); + System.out.println(result1); + var result2 = alphabetSoup("underworld"); + System.out.println(result2); + } + +} diff --git a/src/easy/ArithGeo.java b/src/easy/ArithGeo.java new file mode 100644 index 0000000..c6c361f --- /dev/null +++ b/src/easy/ArithGeo.java @@ -0,0 +1,66 @@ +package easy; + +/** + * Have the function ArithGeo(arr) take the array of numbers stored in arr + * and return the string "Arithmetic" if the sequence follows an arithmetic pattern + * or return "Geometric" if it follows a geometric pattern. + * --- + * If the sequence doesn't follow either pattern return -1. + * An arithmetic sequence is one where the difference between + * each of the numbers is consistent, where in a geometric sequence, + * each term after the first is multiplied by some constant or common ratio. + * --- + * Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. + * Negative numbers may be entered as parameters, 0 will not be entered, + * and no array will contain all the same elements. + */ +public class ArithGeo { + + /** + * Arith Geo function. + * + * @param arr input array of integers + * @return the string "Arithmetic" if the sequence follows an arithmetic pattern + */ + private static String arithGeo(int[] arr) { + + int arithInterval = arr[1] - arr[0]; + int geoInterval = arr[1] / arr[0]; + int arithCount = 0; + int geoCount = 0; + + for (int i = 0; i < arr.length - 1; i++) { + if (arr[i + 1] - arr[i] == arithInterval) { + arithCount++; + } + if (arr[i + 1] / arr[i] == geoInterval) { + geoCount++; + } + } + + if (arithCount == arr.length - 1) { + return "Arithmetic"; + } + + if (geoCount == arr.length - 1) { + return "Geometric"; + } + + return "-1"; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = arithGeo(new int[]{2, 4, 6, 8}); + System.out.println(result1); + var result2 = arithGeo(new int[]{2, 6, 18, 54}); + System.out.println(result2); + var result3 = arithGeo(new int[]{-3, -4, -5, -6, -7}); + System.out.println(result3); + } + +} diff --git a/src/easy/ArrayAdditionOne.java b/src/easy/ArrayAdditionOne.java new file mode 100644 index 0000000..7e97d73 --- /dev/null +++ b/src/easy/ArrayAdditionOne.java @@ -0,0 +1,73 @@ +package easy; + +import static java.lang.Math.pow; + +import java.util.Arrays; + +/** + * Have the function ArrayAdditionI(arr) take the array of numbers stored in arr + * and return the string true if any combination of numbers in the array + * (excluding the largest number) can be added up to equal the largest number in the array, + * otherwise return the string false. + * --- + * For example: if arr contains [4, 6, 23, 10, 1, 3] the output + * should return true because 4 + 6 + 10 + 3 = 23. + * --- + * The array will not be empty, will not contain all the same elements, + * and may contain negative numbers. + */ +public class ArrayAdditionOne { + + /** + * Left pad the string with zeroes, + * e.g. padLeft("fade", 8) -> "0000fade" + * + * @param str string to be padded + * @param len new fixed length after applying the padding + * @return padded string (e.g. 000000xxx) + */ + private static String padLeft(String str, int len) { + return String.format("%" + len + "s", str).replace(" ", "0"); + } + + /** + * Array Addition I function. + * + * @param arr input array of integers + * @return "true" if any combination can be added up to equal the largest number in the array + */ + private static String arrayAdditionOne(int[] arr) { + Arrays.sort(arr); + int largest = arr[arr.length - 1]; + int oneChar = "1".charAt(0); + + for (int i = 0; i < pow(2, arr.length); i++) { + String bin = Integer.toBinaryString(i); + String combo = padLeft(bin, arr.length - 1); + int sum = 0; + for (int j = 0; j < combo.length(); j++) { + if (combo.charAt(j) == oneChar) { + sum += arr[j]; + } + if (sum == largest) { + return "true"; + } + } + } + + return "false"; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = arrayAdditionOne(new int[]{4, 6, 23, 10, 1, 3}); + System.out.println(result1); + var result2 = arrayAdditionOne(new int[]{2, 6, 18}); + System.out.println(result2); + } + +} diff --git a/src/easy/BasicRomanNumerals.java b/src/easy/BasicRomanNumerals.java new file mode 100644 index 0000000..d26df3f --- /dev/null +++ b/src/easy/BasicRomanNumerals.java @@ -0,0 +1,62 @@ +package easy; + +import java.util.HashMap; + +/** + * Have the function BasicRomanNumerals(str) read str which will be a string of Roman numerals. + * The numerals being used are: I for 1, V for 5, X for 10, L for 50, + * C for 100, D for 500 and M for 1000. + * In Roman numerals, to create a number like 11 you simply add a 1 after the 10, + * so you get XI. But to create a number like 19, you use the subtraction notation + * which is to add I before an X or V (or add an X before an L or C). + * So 19 in Roman numerals is XIX. + * --- + * The goal of your program is to return the decimal equivalent of the Roman numeral given. + * For example: if str is "XXIV" your program should return 24 + */ +public class BasicRomanNumerals { + + /** + * Basic Roman Numerals function. + * + * @param str input string + * @return the decimal equivalent of the Roman numeral given + */ + private static int basicRomanNumerals(String str) { + HashMap numerals = new HashMap<>(); + numerals.put("M", 1000); + numerals.put("D", 500); + numerals.put("C", 100); + numerals.put("X", 10); + numerals.put("L", 50); + numerals.put("V", 5); + numerals.put("I", 1); + // reversing the string makes the parsing easier + char[] reversed = new StringBuilder(str).reverse().toString().toCharArray(); + int result = 0; + int prevValue = 0; + for (char cr : reversed) { + int thisValue = numerals.get(Character.toString(cr)); + if (thisValue > prevValue) { + result += thisValue; + } else { + result -= thisValue; + } + prevValue = thisValue; + } + return result; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = basicRomanNumerals("XXIV"); + System.out.println(result1); + var result2 = basicRomanNumerals("XLVI"); + System.out.println(result2); + } + +} diff --git a/src/easy/BinaryReversal.java b/src/easy/BinaryReversal.java new file mode 100644 index 0000000..1804ac8 --- /dev/null +++ b/src/easy/BinaryReversal.java @@ -0,0 +1,58 @@ +package easy; + +/** + * Have the function BinaryReversal(str) take the str parameter being passed, + * which will be a positive integer, take its binary representation + * (padded to the nearest N * 8 bits), reverse that string of bits, + * and then finally return the new reversed string in decimal form. + * --- + * For example: if str is "47" then the binary version of this integer is 101111, + * but we pad it to be 00101111. Your program should reverse this binary string + * which then becomes: 11110100 and then finally return + * the decimal version of this string, which is 244. + */ +public class BinaryReversal { + + /** + * Left pad the string with zeroes, + * e.g. padLeft("fade", 8) -> "0000fade" + * + * @param str string to be padded + * @param len new fixed length after applying the padding + * @return padded string (e.g. 000000xxx) + */ + private static String padLeft(String str, int len) { + return String.format("%" + len + "s", str).replace(" ", "0"); + } + + /** + * Binary Reversal function. + * + * @param str input string + * @return the decimal version of this string + */ + private static int binaryReversal(String str) { + String binStr = Integer.toBinaryString(Integer.parseInt(str)); + int add = binStr.length() % 8 == 0 ? 0 : 1; + int pad = add + binStr.length() / 8; + String padStr = padLeft(binStr, pad * 8); + StringBuilder result = new StringBuilder(); + for (int i = padStr.length() - 1; i >= 0; i--) { + result.append(Character.getNumericValue(padStr.charAt(i))); + } + return Integer.parseInt(result.toString(), 2); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = binaryReversal("47"); + System.out.println(result1); + var result2 = binaryReversal("2"); + System.out.println(result2); + } + +} diff --git a/src/easy/BitwiseOne.java b/src/easy/BitwiseOne.java new file mode 100644 index 0000000..1ab60b9 --- /dev/null +++ b/src/easy/BitwiseOne.java @@ -0,0 +1,47 @@ +package easy; + +/** + * Have the function BitwiseOne(strArr) take the array of strings stored in strArr, + * which will only contain two strings of equal length that represent binary numbers, + * and return a final binary string that performed the bitwise OR operation + * on both strings. + * --- + * A bitwise OR operation places a 0 in the new string + * where there are zeroes in both binary strings, + * otherwise it places a 1 in that spot. + * --- + * For example: if strArr is ["1001", "0100"] then your program + * should return the string "1101" + */ +public class BitwiseOne { + + /** + * Bitwise One function. + * + * @param strArr an array of two binary strings + * @return a binary string that performed the bitwise OR operation on both strings + */ + private static String bitwiseOne(String[] strArr) { + String s1 = strArr[0]; + String s2 = strArr[1]; + StringBuilder result = new StringBuilder(); + for (int i = 0; i < s1.length(); i++) { + int lgOr = Character.getNumericValue(s1.charAt(i)) | Character.getNumericValue(s2.charAt(i)); + result.append(lgOr); + } + return result.toString(); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = bitwiseOne(new String[]{"001110", "100000"}); + System.out.println(result1); + var result2 = bitwiseOne(new String[]{"110001", "111100"}); + System.out.println(result2); + } + +} diff --git a/src/easy/BitwiseTwo.java b/src/easy/BitwiseTwo.java new file mode 100644 index 0000000..869e78a --- /dev/null +++ b/src/easy/BitwiseTwo.java @@ -0,0 +1,45 @@ +package easy; + +/** + * Have the function BitwiseTwo(strArr) take the array of strings stored in strArr, + * which will only contain two strings of equal length that represent binary numbers, + * and return a final binary string that performed the bitwise AND operation on both strings. + * --- + * A bitwise AND operation places a 1 in the new string where + * there is a 1 in both locations in the binary strings, + * otherwise it places a 0 in that spot. For example: + * if strArr is ["10111", "01101"] then your program should return the string "00101" + */ +public class BitwiseTwo { + + /** + * Bitwise Two function. + * + * @param strArr an array of two binary strings + * @return a string that performed the bitwise AND operation on both strings + */ + private static String bitwiseTwo(String[] strArr) { + + String s1 = strArr[0]; + String s2 = strArr[1]; + StringBuilder out = new StringBuilder(); + + for (int i = 0; i < s1.length(); i++) { + int lgAnd = Character.getNumericValue(s1.charAt(i)) & Character.getNumericValue(s2.charAt(i)); + out.append(lgAnd); + } + + return out.toString(); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = bitwiseTwo(new String[]{"10111", "01101"}); + System.out.println(result1); + } + +} diff --git a/src/easy/CamelCase.java b/src/easy/CamelCase.java new file mode 100644 index 0000000..7c03a35 --- /dev/null +++ b/src/easy/CamelCase.java @@ -0,0 +1,65 @@ +package easy; + +/** + * Have the function CamelCase(str) take the str parameter being passed + * and return it in proper camel case format where the first letter + * of each word is capitalized (excluding the first letter). + * --- + * The string will only contain letters and some combination of delimiter + * punctuation characters separating each word. + * For example: if str is "BOB loves-coding" then your program + * should return the string bobLovesCoding. + */ +public class CamelCase { + + /** + * A helper function which removes non-alphabetic characters, + * converts to a lower case and trims the string. + * + * @param str input string + * @return a string with non-alphabetic characters removed + */ + private static String[] splitWords(String str) { + return str + .toLowerCase() + .replaceAll("([^a-z])", " ") + .replaceAll(" +", " ") + .trim().split(" "); + } + + /** + * Camel Case function. + * + * @param str input string + * @return a string in proper camel case format + */ + private static String camelCase(String str) { + StringBuilder camel = new StringBuilder(); + String[] words = splitWords(str); + int index = 0; + for (String word : words) { + if (index == 0) { + camel.append(word); + } else { + camel.append(word.substring(0, 1).toUpperCase()).append(word.substring(1)); + } + index++; + } + return camel.toString(); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = camelCase("_good_looking_blues_"); + System.out.println(result1); + + var result2 = camelCase("-=last-night-on-earth=-"); + System.out.println(result2); + + } + +} diff --git a/src/easy/CheckNums.java b/src/easy/CheckNums.java new file mode 100644 index 0000000..fc66563 --- /dev/null +++ b/src/easy/CheckNums.java @@ -0,0 +1,39 @@ +package easy; + +/** + * Have the function CheckNums(num1,num2) take both parameters + * being passed and return the string true if num2 is greater + * than num1, otherwise return the string false. + * If the parameter values are equal to each other, then return the string -1. + */ +public class CheckNums { + + /** + * Check Nums function. + * + * @param num1 first number to compare + * @param num2 second number to compare + * @return result of the comparison + */ + private static String checkNums(int num1, int num2) { + if (num1 == num2) { + return "-1"; + } + return num2 > num1 ? "true" : "false"; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = checkNums(63, 16); + System.out.println(result1); + var result2 = checkNums(50, 50); + System.out.println(result2); + var result3 = checkNums(70, 60); + System.out.println(result3); + } + +} diff --git a/src/easy/DashInsert.java b/src/easy/DashInsert.java new file mode 100644 index 0000000..649fe36 --- /dev/null +++ b/src/easy/DashInsert.java @@ -0,0 +1,43 @@ +package easy; + +/** + * Have the function DashInsert(str) insert dashes ('-') + * between each two odd numbers in str. For example: + * if str is 454793 the output should be 4547-9-3. + * Don't count zero as an odd number. + */ +public class DashInsert { + + /** + * Dash Insert function. + * + * @param str input string + * @return a string with dashes between each two odd numbers + */ + private static String dashInsert(String str) { + StringBuilder dashed = new StringBuilder(); + char[] chars = str.toCharArray(); + for (int i = 1; i < chars.length + 1; i++) { + int c1 = Character.getNumericValue(chars[i - 1]); + int c2 = i < chars.length ? Character.getNumericValue(chars[i]) : 0; + dashed.append(c1); + if (c1 % 2 != 0 && c2 % 2 != 0) { + dashed.append("-"); + } + } + return dashed.toString(); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = dashInsert("454793"); + System.out.println(result1); + var result2 = dashInsert("25928"); + System.out.println(result2); + } + +} diff --git a/src/easy/DistinctCharacters.java b/src/easy/DistinctCharacters.java new file mode 100644 index 0000000..75d0518 --- /dev/null +++ b/src/easy/DistinctCharacters.java @@ -0,0 +1,44 @@ +package easy; + +import java.util.HashSet; +import java.util.Set; + +/** + * Have the function DistinctCharacters(str) take the str parameter being passed + * and determine if it contains at least 10 distinct characters, + * if so, then your program should return the string true, + * otherwise it should return the string false. + * --- + * For example: if str is "abc123kkmmmm?" then your program should return the string false + * because this string contains only 9 distinct characters: + * a, b, c, 1, 2, 3, k, m. ? adds up to 9. + */ +public class DistinctCharacters { + + /** + * Distinct Characters function. + * + * @param str input string + * @return "true" if a string contains at least 10 distinct characters. + */ + private static String distinctCharacters(String str) { + Set table = new HashSet<>(); + for (int i = 0; i < str.length(); i++) { + table.add(str.charAt(i)); + } + return table.size() >= 10 ? "true" : "false"; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = distinctCharacters("12334bbmma:=6"); + System.out.println(result1); + var result2 = distinctCharacters("001122334455667788"); + System.out.println(result2); + } + +} diff --git a/src/easy/ExOh.java b/src/easy/ExOh.java new file mode 100644 index 0000000..890dc01 --- /dev/null +++ b/src/easy/ExOh.java @@ -0,0 +1,49 @@ +package easy; + +/** + * Have the function ExOh(str) take the str parameter being passed + * and return the string true if there is an equal number of x's and o's, + * otherwise return the string false. Only these two letters + * will be entered in the string, no punctuation or numbers. + * For example: if str is "xooxxxxooxo" then the output + * should return false because there are 6 x's and 5 o's. + */ +public class ExOh { + + /** + * EX OH function. + * + * @param str input string + * @return "true" if there is an equal number of x's and o's + */ + private static String exOh(String str) { + int balance = 0; + String[] letters = str.toLowerCase().split(""); + for (String l : letters) { + switch (l) { + case "x": + balance++; + break; + case "o": + balance--; + break; + default: + break; + } + } + return balance == 0 || str.length() == 0 ? "true" : "false"; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = exOh("xxxooo"); + System.out.println(result1); + var result2 = exOh("xxxoo"); + System.out.println(result2); + } + +} diff --git a/src/easy/FindIntersection.java b/src/easy/FindIntersection.java new file mode 100644 index 0000000..f88ecec --- /dev/null +++ b/src/easy/FindIntersection.java @@ -0,0 +1,86 @@ +package easy; + +/** + * Have the function FindIntersection(strArr) read the array of strings + * stored in strArr which will contain 2 elements: the first element + * will represent a list of comma-separated numbers sorted in ascending order, + * the second element will represent a second list of comma-separated numbers (also sorted). + * Your goal is to return a comma-separated string containing + * the numbers that occur in elements of strArr in sorted order. + * If there is no intersection, return the string false. + */ +public class FindIntersection { + + /** + * Binary Search helper function. + * + * @param coll an array of integers + * @param key a value to find + * @return index of the key + */ + private static int binarySearch(Integer[] coll, Integer key) { + int lo = 0; + int hi = coll.length - 1; + while (lo <= hi) { + int mid = lo + (hi - lo) / 2; + if (key < coll[mid]) { + hi = mid - 1; + } else if (key > coll[mid]) { + lo = mid + 1; + } else { + return mid; + } + } + return -1; + } + + /** + * Convert a string to an array of integers. + * + * @param strArr comma-delimited string of numbers + * @return array of integers + */ + private static Integer[] toIntArray(String strArr) { + String[] tmpArr = strArr.split(", "); + Integer[] intArr = new Integer[tmpArr.length]; + for (int i = 0; i < tmpArr.length; i++) { + intArr[i] = Integer.parseInt(tmpArr[i].trim()); + } + return intArr; + } + + /** + * Find Intersection function. + * + * @param arr input array containing two strings of comma-delimited integers + * @return the numbers that occur in elements of strArr in sorted order. + */ + private static String findIntersection(String[] arr) { + Integer[] arr1 = toIntArray(arr[0]); + Integer[] arr2 = toIntArray(arr[1]); + StringBuilder builder = new StringBuilder(); + for (int i : arr1.length > arr2.length ? arr2 : arr1) { + int findIndex = binarySearch(arr1.length > arr2.length ? arr1 : arr2, i); + if (findIndex > -1) { + builder.append(i).append(","); + } + } + String result = builder.toString(); + return result.length() == 0 ? "false" : builder.substring(0, result.length() - 1); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = findIntersection(new String[]{"11, 12, 14, 16, 20", "11, 12, 13, 18, 21"}); + System.out.println(result1); + var result2 = findIntersection(new String[]{"1, 3, 4, 7, 13", "1, 2, 4, 13, 15"}); + System.out.println(result2); + var result3 = findIntersection(new String[]{"21, 22, 23, 25, 27, 28", "21, 24, 25, 29"}); + System.out.println(result3); + } + +} diff --git a/src/easy/FirstFactorial.java b/src/easy/FirstFactorial.java new file mode 100644 index 0000000..823c1a5 --- /dev/null +++ b/src/easy/FirstFactorial.java @@ -0,0 +1,39 @@ +package easy; + +/** + * Have the function FirstFactorial(num) take + * the num parameter being passed and return the factorial of it. + * For example: if num = 4, then your program + * should return (4 * 3 * 2 * 1) = 24. + * For the test cases, the range will be between 1 and 18 + * and the input will always be an integer. + */ +public class FirstFactorial { + + /** + * First Factorial function. + * + * @param num input number + * @return facorial of the given number + */ + private static int firstFactorial(int num) { + if (num == 0) { + return 1; + } else { + return num * firstFactorial(num - 1); + } + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = firstFactorial(4); + System.out.println(result1); + var result2 = firstFactorial(8); + System.out.println(result2); + } + +} diff --git a/src/easy/FirstReverse.java b/src/easy/FirstReverse.java new file mode 100644 index 0000000..036f68b --- /dev/null +++ b/src/easy/FirstReverse.java @@ -0,0 +1,33 @@ +package easy; + +/** + * Have the function FirstReverse(str) take the str parameter + * being passed and return the string in reversed order. + * For example: if the input string is "Hello World and Coders" + * then your program should return the string sredoC dna dlroW olleH. + */ +public class FirstReverse { + + /** + * First Reverse function. + * + * @param str input string + * @return reversed string + */ + private static String firstReverse(String str) { + return new StringBuilder(str).reverse().toString(); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = firstReverse("Hello World and Coders"); + System.out.println(result1); + var result2 = firstReverse("Good Looking Blues"); + System.out.println(result2); + } + +} diff --git a/src/easy/Gcf.java b/src/easy/Gcf.java new file mode 100644 index 0000000..3a8fd0e --- /dev/null +++ b/src/easy/Gcf.java @@ -0,0 +1,39 @@ +package easy; + +/** + * Have the function GCF(arr) take the array of numbers stored in arr + * which will always contain only two positive integers, + * and return the greatest common factor of them. + * --- + * For example: if arr is [45, 12] then your program should return 3. + * There will always be two elements in the array, + * and they will be positive integers. + */ +public class Gcf { + + /** + * Greatest Common Factor function. + * + * @param arr input array of integers + * @return the greatest common factor + */ + private static int gcf(int[] arr) { + if (arr[0] == 0 || arr[1] == 0) { + return arr[0] + arr[1]; + } + return gcf(new int[]{arr[1], arr[0] % arr[1]}); + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + var result1 = gcf(new int[]{64, 128, 256, 512}); + System.out.println(result1); + var result2 = gcf(new int[]{12, 28}); + System.out.println(result2); + } + +} diff --git a/src/easy/LargestFour.java b/src/easy/LargestFour.java new file mode 100644 index 0000000..32aceae --- /dev/null +++ b/src/easy/LargestFour.java @@ -0,0 +1,111 @@ +package easy; + +/** + * Have the function LargestFour(arr) take the array of integers stored in arr, + * and find the four largest elements and return their sum. + * -- + * For example: if arr is [4, 5, -2, 3, 1, 2, 6, 6] + * then the four largest elements in this array are 6, 6, 4, and 5 + * and the total sum of these numbers is 21, so your program should return 21. + * -- + * If there are less than four numbers in the array your program + * should return the sum of all the numbers in the array. + */ +public class LargestFour { + + /** + * QuickSelect implementation based on Sedgewick R., Wayne K., Algorithms 4th edn. + * + * @param a input array + * @param k k-smallest element in the list + */ + private static void select(int[] a, int k) { + int lo = 0; + int hi = a.length - 1; + while (hi > lo) { + int i = partition(a, lo, hi); + if (i > k) { + hi = i - 1; + } else if (i >= k) { + return; + } else { + lo = i + 1; + } + } + } + + private static int partition(int[] a, int lo, int hi) { + int i = lo; + int j = hi + 1; + int v = a[lo]; + while (true) { + // find item on lo to swap + while (less(a[++i], v)) { + if (i == hi) { + break; + } + } + // find item on hi to swap + while (less(v, a[--j])) { + if (j == lo) { + break; // redundant since a[lo] acts as sentinel + } + } + // check if pointers cross + if (i >= j) { + break; + } + exchange(a, i, j); + } + // put partitioning item v at a[j] + exchange(a, lo, j); + // now, a[lo .. j-1] <= a[j] <= a[j+1 .. hi] + return j; + } + + private static boolean less(Comparable v, Comparable w) { + return v.compareTo((Integer) w) < 0; + } + + // exchange a[i] and a[j] + private static void exchange(int[] a, int i, int j) { + int swap = a[i]; + a[i] = a[j]; + a[j] = swap; + } + + private static int largestFour(int[] arr) { + int sum = 0; + if (arr.length <= 4) { + for (int i : arr) { + sum += i; + } + return sum; + } + int k = arr.length - 4; + select(arr, k); + for (int i = k; i < arr.length; i++) { + sum += arr[i]; + } + return sum; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + int[] arr1 = new int[]{5, 6, 10, 12, 1, 1, 1, 5}; + int result1 = largestFour(arr1); + System.out.println(result1); + + int[] arr2 = new int[]{0, 0, 2, 3, 7, 1}; + int result2 = largestFour(arr2); + System.out.println(result2); + + int[] arr3 = new int[]{5, 6, 10, 12, 1, 1, 1, 5}; + int result3 = largestFour(arr3); + System.out.println(result3); + } +} diff --git a/src/easy/LargestPair.java b/src/easy/LargestPair.java new file mode 100644 index 0000000..8d5805c --- /dev/null +++ b/src/easy/LargestPair.java @@ -0,0 +1,45 @@ +package easy; + +/** + * Have the function LargestPair(num) take the num parameter being passed + * and determine the largest double-digit number within the whole number. + * --- + * For example: if num is 4759472 then your program should return 94 because + * that is the largest double-digit number. + * The input will always contain at least two positive digits. + */ +public class LargestPair { + + /** + * Largest pair function. + * + * @param num input number + * @return the largest double-digit number within the whole number + */ + private static int largestPair(int num) { + int largest = Integer.MIN_VALUE; + String numstr = Integer.toString(num); + for (int i = 0; i < numstr.length() - 1; i++) { + int i1 = Integer.parseInt(String.valueOf(numstr.charAt(i))); + int i2 = Integer.parseInt(String.valueOf(numstr.charAt(i + 1))); + int pair = i1 * 10 + i2; + if (pair > largest) { + largest = pair; + } + } + return largest; + } + + /** + * Entry point. + * + * @param args command line arguments + */ + public static void main(String[] args) { + int result1 = largestPair(567353664); + System.out.println(result1); + int result2 = largestPair(8163264); + System.out.println(result2); + } + +} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy