├── CheckVowels.java ├── Conversions ├── AnyBaseToAnyBase.java ├── AnyBaseToDecimal.java ├── AnytoAny.java ├── BinaryToDecimal.java ├── BinaryToHexadecimal.java ├── BinaryToOctal.java ├── DecimalToAnyBase.java ├── DecimalToBinary.java ├── DecimalToHexaDecimal.java ├── DecimalToOctal.java ├── HexToOct.java ├── HexaDecimalToBinary.java ├── HexaDecimalToDecimal.java ├── IntegerToRoman.java ├── OctalToDecimal.java ├── OctalToHexadecimal.java ├── README.md ├── RgbHsvConversion.java ├── RomanToInteger.java └── TurkishToLatinConversion.java ├── Misc ├── ColorContrastRatio.java ├── InverseOfMatrix.java ├── MedianOfRunningArray.java ├── PalindromePrime.java ├── PalindromeSinglyLinkedList.java ├── README.md ├── RangeInSortedArray.java ├── Sort012D.java ├── Sparcity.java ├── ThreeSumProblem.java ├── TwoSumProblem.java ├── WordBoggle.java └── matrixTranspose.java ├── Others ├── ArrayLeftRotation.java ├── BFPRT.java ├── BankersAlgorithm.java ├── BoyerMoore.java ├── BrianKernighanAlgorithm.java ├── CPUalgorithms.java ├── CRC32.java ├── CRCAlgorithm.java ├── CountChar.java ├── CountWords.java ├── Damm.java ├── Dijkstra.java ├── EulersFunction.java ├── FibbonaciSeries.java ├── FloydTriangle.java ├── GuassLegendre.java ├── HappyNumbersSeq.java ├── Huffman.java ├── Implementing_auto_completing_features_using_trie.java ├── InsertDeleteInArray.java ├── KMP.java ├── KochSnowflake.java ├── Krishnamurthy.java ├── LinearCongruentialGenerator.java ├── LowestBasePalindrome.java ├── Luhn.java ├── Mandelbrot.java ├── MiniMaxAlgorithm.java ├── PageRank.java ├── PasswordGen.java ├── PerlinNoise.java ├── QueueUsingTwoStacks.java ├── README.md ├── RabinKarp.java ├── RemoveDuplicateFromString.java ├── ReturnSubsequence.java ├── ReverseStackUsingRecursion.java ├── RootPrecision.java ├── RotateMatriceBy90Degree.java ├── SJF.java ├── SieveOfEratosthenes.java ├── SkylineProblem.java ├── StackPostfixNotation.java ├── StringMatchFiniteAutomata.java ├── Sudoku.java ├── ThreeSum.java ├── TopKWords.java ├── TowerOfHanoi.java ├── TwoPointers.java └── Verhoeff.java ├── README.md ├── Searches ├── BinarySearch.java ├── BreadthFirstSearch.java ├── DepthFirstSearch.java ├── ExponentalSearch.java ├── FibonacciSearch.java ├── HowManyTimesRotated.java ├── InterpolationSearch.java ├── IterativeBinarySearch.java ├── IterativeTernarySearch.java ├── JumpSearch.java ├── LinearSearch.java ├── LinearSearchThread.java ├── LowerBound.java ├── MonteCarloTreeSearch.java ├── PerfectBinarySearch.java ├── QuickSelect.java ├── README.md ├── SaddlebackSearch.java ├── SquareRootBinarySearch.java ├── TernarySearch.java ├── UnionFind.java └── UpperBound.java └── Strings ├── Alphabetical.java ├── Anagrams.java ├── CharactersSame.java ├── CheckAnagrams.java ├── CheckVowels.java ├── HorspoolSearch.java ├── List_all_Possible_Words_From_Phone_Digits.java ├── LongestPalindromicSubstring.java ├── Lower.java ├── Palindrome.java ├── Pangram.java ├── PermuteString.java ├── README.md ├── ReverseString.java ├── Rotation.java ├── Upper.java └── WordLadder.java /CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Vowel Count is a system whereby character strings are placed in order based 9 | * on the position of the characters in the conventional ordering of an 10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 11 | */ 12 | public class CheckVowels { 13 | private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); 14 | 15 | /** 16 | * Check if a string is has vowels or not 17 | * 18 | * @param input a string 19 | * @return {@code true} if given string has vowels, otherwise {@code false} 20 | */ 21 | public static boolean hasVowels(String input) { 22 | return countVowels(input) > 0; 23 | } 24 | 25 | /** 26 | * count the number of vowels 27 | * 28 | * @param input a string prints the count of vowels 29 | */ 30 | public static int countVowels(String input) { 31 | if (input == null) { 32 | return 0; 33 | } 34 | int cnt = 0; 35 | for (char c : input.toLowerCase().toCharArray()) { 36 | if (VOWELS.contains(c)) { 37 | ++cnt; 38 | } 39 | } 40 | return cnt; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Conversions/AnyBaseToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | // Driver program 7 | public class AnyBaseToDecimal { 8 | 9 | public static void main(String[] args) { 10 | assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2); 11 | assert convertToDecimal("777", 8) == Integer.valueOf("777", 8); 12 | assert convertToDecimal("999", 10) == Integer.valueOf("999", 10); 13 | assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16); 14 | assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36); 15 | } 16 | 17 | /** 18 | * Convert any radix to decimal number 19 | * 20 | * @param s the string to be convert 21 | * @param radix the radix 22 | * @return decimal of bits 23 | * @throws NumberFormatException if {@code bits} or {@code radix} is invalid 24 | */ 25 | public static int convertToDecimal(String s, int radix) { 26 | int num = 0; 27 | int pow = 1; 28 | 29 | for (int i = s.length() - 1; i >= 0; i--) { 30 | int digit = valOfChar(s.charAt(i)); 31 | if (digit >= radix) { 32 | throw new NumberFormatException("For input string " + s); 33 | } 34 | num += valOfChar(s.charAt(i)) * pow; 35 | pow *= radix; 36 | } 37 | return num; 38 | } 39 | 40 | /** 41 | * Convert character to integer 42 | * 43 | * @param c the character 44 | * @return represented digit of given character 45 | * @throws NumberFormatException if {@code ch} is not UpperCase or Digit 46 | * character. 47 | */ 48 | public static int valOfChar(char c) { 49 | if (!(Character.isUpperCase(c) || Character.isDigit(c))) { 50 | throw new NumberFormatException("invalid character :" + c); 51 | } 52 | return Character.isDigit(c) ? c - '0' : c - 'A' + 10; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | // given a source number , source base, destination base, this code can give you the destination 5 | // number. 6 | // sn ,sb,db ---> ()dn . this is what we have to do . 7 | 8 | public class AnytoAny { 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | int sn = scn.nextInt(); 13 | int sb = scn.nextInt(); 14 | int db = scn.nextInt(); 15 | int m = 1, dec = 0, dn = 0; 16 | while (sn != 0) { 17 | dec = dec + (sn % 10) * m; 18 | m *= sb; 19 | sn /= 10; 20 | } 21 | m = 1; 22 | while (dec != 0) { 23 | dn = dn + (dec % db) * m; 24 | m *= 10; 25 | dec /= db; 26 | } 27 | System.out.println(dn); 28 | scn.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | */ 8 | class BinaryToDecimal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line arguments 14 | */ 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int binNum, binCopy, d, s = 0, power = 0; 18 | System.out.print("Binary number: "); 19 | binNum = sc.nextInt(); 20 | binCopy = binNum; 21 | while (binCopy != 0) { 22 | d = binCopy % 10; 23 | s += d * (int) Math.pow(2, power++); 24 | binCopy /= 10; 25 | } 26 | System.out.println("Decimal equivalent:" + s); 27 | sc.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Conversions/BinaryToHexadecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * Converts any Binary Number to a Hexadecimal Number 7 | * 8 | * @author Nishita Aggarwal 9 | */ 10 | public class BinaryToHexadecimal { 11 | 12 | /** 13 | * This method converts a binary number to a hexadecimal number. 14 | * 15 | * @param binary The binary number 16 | * @return The hexadecimal number 17 | */ 18 | static String binToHex(int binary) { 19 | // hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for 20 | // decimal numbers 0 to 15 21 | HashMap hm = new HashMap<>(); 22 | // String to store hexadecimal code 23 | String hex = ""; 24 | int i; 25 | for (i = 0; i < 10; i++) { 26 | hm.put(i, String.valueOf(i)); 27 | } 28 | for (i = 10; i < 16; i++) { 29 | hm.put(i, String.valueOf((char) ('A' + i - 10))); 30 | } 31 | int currbit; 32 | while (binary != 0) { 33 | int code4 = 0; // to store decimal equivalent of number formed by 4 decimal digits 34 | for (i = 0; i < 4; i++) { 35 | currbit = binary % 10; 36 | binary = binary / 10; 37 | code4 += currbit * Math.pow(2, i); 38 | } 39 | hex = hm.get(code4) + hex; 40 | } 41 | return hex; 42 | } 43 | 44 | /** 45 | * Main method 46 | * 47 | * @param args Command line arguments 48 | */ 49 | public static void main(String[] args) { 50 | Scanner sc = new Scanner(System.in); 51 | System.out.println("Enter binary number:"); 52 | int binary = sc.nextInt(); 53 | String hex = binToHex(binary); 54 | System.out.println("Hexadecimal Code:" + hex); 55 | sc.close(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Conversions/BinaryToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Binary number to an Octal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class BinaryToOctal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the binary number: "); 20 | int b = sc.nextInt(); 21 | System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a binary number to an octal number. 27 | * 28 | * @param binary The binary number 29 | * @return The octal number 30 | */ 31 | public static String convertBinaryToOctal(int binary) { 32 | String octal = ""; 33 | int currBit = 0, j = 1; 34 | while (binary != 0) { 35 | int code3 = 0; 36 | for (int i = 0; i < 3; i++) { 37 | currBit = binary % 10; 38 | binary = binary / 10; 39 | code3 += currBit * j; 40 | j *= 2; 41 | } 42 | octal = code3 + octal; 43 | j = 1; 44 | } 45 | return octal; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Conversions/DecimalToAnyBase.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.util.ArrayList; 6 | 7 | /** 8 | * @author Varun Upadhyay (https://github.com/varunu28) 9 | */ 10 | // Driver Program 11 | public class DecimalToAnyBase { 12 | 13 | public static void main(String[] args) throws Exception { 14 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 15 | System.out.println("Enter the decimal input below: "); 16 | int decInput = Integer.parseInt(br.readLine()); 17 | System.out.println(); 18 | 19 | System.out.println("Enter the base below: "); 20 | int base = Integer.parseInt(br.readLine()); 21 | System.out.println(); 22 | 23 | System.out.println("Decimal Input" + " is: " + decInput); 24 | System.out.println( 25 | "Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); 26 | 27 | br.close(); 28 | } 29 | 30 | /** 31 | * This method produces a String value of any given input decimal in any 32 | * base 33 | * 34 | * @param inp Decimal of which we need the value in base in String format 35 | * @return string format of the converted value in the given base 36 | */ 37 | public static String convertToAnyBase(int inp, int base) { 38 | ArrayList charArr = new ArrayList<>(); 39 | 40 | while (inp > 0) { 41 | charArr.add(reVal(inp % base)); 42 | inp /= base; 43 | } 44 | 45 | StringBuilder str = new StringBuilder(charArr.size()); 46 | 47 | for (Character ch : charArr) { 48 | str.append(ch); 49 | } 50 | 51 | return str.reverse().toString(); 52 | } 53 | 54 | /** 55 | * This method produces character value of the input integer and returns it 56 | * 57 | * @param num integer of which we need the character value of 58 | * @return character value of input integer 59 | */ 60 | public static char reVal(int num) { 61 | if (num >= 0 && num <= 9) { 62 | return (char) (num + '0'); 63 | } else { 64 | return (char) (num - 10 + 'A'); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Conversions/DecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Decimal number to a Binary number 7 | */ 8 | class DecimalToBinary { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command Line Arguments 14 | */ 15 | public static void main(String args[]) { 16 | conventionalConversion(); 17 | bitwiseConversion(); 18 | } 19 | 20 | /** 21 | * This method converts a decimal number to a binary number using a 22 | * conventional algorithm. 23 | */ 24 | public static void conventionalConversion() { 25 | int n, b = 0, c = 0, d; 26 | Scanner input = new Scanner(System.in); 27 | System.out.printf("Conventional conversion.%n Enter the decimal number: "); 28 | n = input.nextInt(); 29 | while (n != 0) { 30 | d = n % 2; 31 | b = b + d * (int) Math.pow(10, c++); 32 | n /= 2; 33 | } // converting decimal to binary 34 | System.out.println("\tBinary number: " + b); 35 | input.close(); 36 | } 37 | 38 | /** 39 | * This method converts a decimal number to a binary number using a bitwise 40 | * algorithm 41 | */ 42 | public static void bitwiseConversion() { 43 | int n, b = 0, c = 0, d; 44 | Scanner input = new Scanner(System.in); 45 | System.out.printf("Bitwise conversion.%n Enter the decimal number: "); 46 | n = input.nextInt(); 47 | while (n != 0) { 48 | d = (n & 1); 49 | b += d * (int) Math.pow(10, c++); 50 | n >>= 1; 51 | } 52 | System.out.println("\tBinary number: " + b); 53 | input.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Conversions/DecimalToHexaDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // hex = [0 - 9] -> [A - F] 4 | class DecimalToHexaDecimal { 5 | 6 | private static final int sizeOfIntInHalfBytes = 8; 7 | private static final int numberOfBitsInAHalfByte = 4; 8 | private static final int halfByte = 0x0F; 9 | private static final char[] hexDigits = { 10 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 11 | }; 12 | 13 | // Returns the hex value of the dec entered in the parameter. 14 | public static String decToHex(int dec) { 15 | StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); 16 | hexBuilder.setLength(sizeOfIntInHalfBytes); 17 | for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { 18 | int j = dec & halfByte; 19 | hexBuilder.setCharAt(i, hexDigits[j]); 20 | dec >>= numberOfBitsInAHalfByte; 21 | } 22 | return hexBuilder.toString().toLowerCase(); 23 | } 24 | 25 | // Test above function. 26 | public static void main(String[] args) { 27 | System.out.println("Test..."); 28 | int dec = 305445566; 29 | String libraryDecToHex = Integer.toHexString(dec); 30 | String decToHex = decToHex(dec); 31 | System.out.println("Result from the library : " + libraryDecToHex); 32 | System.out.println("Result decToHex method : " + decToHex); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | */ 8 | public class DecimalToOctal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line Arguments 14 | */ 15 | 16 | // enter in a decimal value to get Octal output 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n, k, d, s = 0, c = 0; 20 | System.out.print("Decimal number: "); 21 | n = sc.nextInt(); 22 | k = n; 23 | while (k != 0) { 24 | d = k % 8; 25 | s += d * (int) Math.pow(10, c++); 26 | k /= 8; 27 | } 28 | 29 | System.out.println("Octal equivalent:" + s); 30 | sc.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Conversions/HexToOct.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Hexadecimal Number to Octal 7 | * 8 | * @author Tanmay Joshi 9 | */ 10 | public class HexToOct { 11 | 12 | /** 13 | * This method converts a Hexadecimal number to a decimal number 14 | * 15 | * @param s The Hexadecimal Number 16 | * @return The Decimal number 17 | */ 18 | public static int hex2decimal(String s) { 19 | String str = "0123456789ABCDEF"; 20 | s = s.toUpperCase(); 21 | int val = 0; 22 | for (int i = 0; i < s.length(); i++) { 23 | char a = s.charAt(i); 24 | int n = str.indexOf(a); 25 | val = 16 * val + n; 26 | } 27 | return val; 28 | } 29 | 30 | /** 31 | * This method converts a Decimal number to a octal number 32 | * 33 | * @param q The Decimal Number 34 | * @return The Octal number 35 | */ 36 | public static int decimal2octal(int q) { 37 | int now; 38 | int i = 1; 39 | int octnum = 0; 40 | while (q > 0) { 41 | now = q % 8; 42 | octnum = (now * (int) (Math.pow(10, i))) + octnum; 43 | q /= 8; 44 | i++; 45 | } 46 | octnum /= 10; 47 | return octnum; 48 | } 49 | 50 | /** 51 | * Main method that gets the hex input from user and converts it into octal. 52 | * 53 | * @param args arguments 54 | */ 55 | public static void main(String args[]) { 56 | String hexadecnum; 57 | int decnum, octalnum; 58 | Scanner scan = new Scanner(System.in); 59 | 60 | System.out.print("Enter Hexadecimal Number : "); 61 | hexadecnum = scan.nextLine(); 62 | 63 | // first convert hexadecimal to decimal 64 | decnum 65 | = hex2decimal( 66 | hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in 67 | // variable decnum 68 | 69 | // convert decimal to octal 70 | octalnum = decimal2octal(decnum); 71 | System.out.println("Number in octal: " + octalnum); 72 | scan.close(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Conversions/HexaDecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // Hex [0-9],[A-F] -> Binary [0,1] 4 | public class HexaDecimalToBinary { 5 | 6 | private final int LONG_BITS = 8; 7 | 8 | public void convert(String numHex) { 9 | // String a HexaDecimal: 10 | int conHex = Integer.parseInt(numHex, 16); 11 | // Hex a Binary: 12 | String binary = Integer.toBinaryString(conHex); 13 | // Output: 14 | System.out.println(numHex + " = " + completeDigits(binary)); 15 | } 16 | 17 | public String completeDigits(String binNum) { 18 | for (int i = binNum.length(); i < LONG_BITS; i++) { 19 | binNum = "0" + binNum; 20 | } 21 | return binNum; 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | // Testing Numbers: 27 | String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; 28 | HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); 29 | 30 | for (String num : hexNums) { 31 | objConvert.convert(num); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Conversions/HexaDecimalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HexaDecimalToDecimal { 6 | 7 | // convert hexadecimal to decimal 8 | public static int getHexaToDec(String hex) { 9 | String digits = "0123456789ABCDEF"; 10 | hex = hex.toUpperCase(); 11 | int val = 0; 12 | for (int i = 0; i < hex.length(); i++) { 13 | int d = digits.indexOf(hex.charAt(i)); 14 | val = 16 * val + d; 15 | } 16 | return val; 17 | } 18 | 19 | // Main method gets the hexadecimal input from user and converts it into Decimal output. 20 | public static void main(String args[]) { 21 | String hexa_Input; 22 | int dec_output; 23 | Scanner scan = new Scanner(System.in); 24 | 25 | System.out.print("Enter Hexadecimal Number : "); 26 | hexa_Input = scan.nextLine(); 27 | 28 | // convert hexadecimal to decimal 29 | dec_output = getHexaToDec(hexa_Input); 30 | /* 31 | Pass the string to the getHexaToDec function 32 | and it returns the decimal form in the variable dec_output. 33 | */ 34 | System.out.println("Number in Decimal: " + dec_output); 35 | scan.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Conversions/IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | /** 4 | * Converting Integers into Roman Numerals 5 | * 6 | *

7 | * ('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50); 8 | * ('XC',90); ('C', 100); ('D', 500); ('M', 1000); 9 | */ 10 | public class IntegerToRoman { 11 | 12 | private static int[] allArabianRomanNumbers 13 | = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 14 | private static String[] allRomanNumbers 15 | = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 16 | 17 | // Value must be > 0 18 | public static String integerToRoman(int num) { 19 | if (num <= 0) { 20 | return ""; 21 | } 22 | 23 | StringBuilder builder = new StringBuilder(); 24 | 25 | for (int a = 0; a < allArabianRomanNumbers.length; a++) { 26 | int times = num / allArabianRomanNumbers[a]; 27 | for (int b = 0; b < times; b++) { 28 | builder.append(allRomanNumbers[a]); 29 | } 30 | 31 | num -= times * allArabianRomanNumbers[a]; 32 | } 33 | 34 | return builder.toString(); 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println(IntegerToRoman.integerToRoman(2131)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Conversions/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to a Decimal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class OctalToDecimal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.print("Octal Input: "); 20 | String inputOctal = sc.nextLine(); 21 | int result = convertOctalToDecimal(inputOctal); 22 | if (result != -1) { 23 | System.out.println("Result convertOctalToDecimal : " + result); 24 | } 25 | sc.close(); 26 | } 27 | 28 | /** 29 | * This method converts an octal number to a decimal number. 30 | * 31 | * @param inputOctal The octal number 32 | * @return The decimal number 33 | */ 34 | public static int convertOctalToDecimal(String inputOctal) { 35 | 36 | try { 37 | // Actual conversion of Octal to Decimal: 38 | Integer outputDecimal = Integer.parseInt(inputOctal, 8); 39 | return outputDecimal; 40 | } catch (NumberFormatException ne) { 41 | // Printing a warning message if the input is not a valid octal 42 | // number: 43 | System.out.println("Invalid Input, Expecting octal number 0-7"); 44 | return -1; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Conversions/OctalToHexadecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to HexaDecimal 7 | * 8 | * @author Tanmay Joshi 9 | */ 10 | public class OctalToHexadecimal { 11 | 12 | /** 13 | * This method converts a Octal number to a decimal number 14 | * 15 | * @param s The Octal Number 16 | * @return The Decimal number 17 | */ 18 | public static int octToDec(String s) { 19 | int i = 0; 20 | for (int j = 0; j < s.length(); j++) { 21 | char num = s.charAt(j); 22 | num -= '0'; 23 | i *= 8; 24 | i += num; 25 | } 26 | return i; 27 | } 28 | 29 | /** 30 | * This method converts a Decimal number to a Hexadecimal number 31 | * 32 | * @param d The Decimal Number 33 | * @return The Hexadecimal number 34 | */ 35 | public static String decimalToHex(int d) { 36 | String digits = "0123456789ABCDEF"; 37 | if (d <= 0) { 38 | return "0"; 39 | } 40 | String hex = ""; 41 | while (d > 0) { 42 | int digit = d % 16; 43 | hex = digits.charAt(digit) + hex; 44 | d = d / 16; 45 | } 46 | return hex; 47 | } 48 | 49 | public static void main(String args[]) { 50 | 51 | Scanner input = new Scanner(System.in); 52 | System.out.print("Enter the Octal number: "); 53 | // Take octal number as input from user in a string 54 | String oct = input.next(); 55 | 56 | // Pass the octal number to function and get converted decimal form 57 | int decimal = octToDec(oct); 58 | 59 | // Pass the decimal number to function and get converted Hex form of the number 60 | String hex = decimalToHex(decimal); 61 | System.out.println("The Hexadecimal equivalant is: " + hex); 62 | input.close(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Conversions/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Conversions/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.*; 4 | 5 | public class RomanToInteger { 6 | 7 | private static Map map 8 | = new HashMap() { 9 | /** 10 | * */ 11 | private static final long serialVersionUID = 87605733047260530L; 12 | 13 | { 14 | put('I', 1); 15 | put('V', 5); 16 | put('X', 10); 17 | put('L', 50); 18 | put('C', 100); 19 | put('D', 500); 20 | put('M', 1000); 21 | } 22 | }; 23 | // Roman Number = Roman Numerals 24 | 25 | /** 26 | * This function convert Roman number into Integer 27 | * 28 | * @param A Roman number string 29 | * @return integer 30 | */ 31 | public static int romanToInt(String A) { 32 | 33 | A = A.toUpperCase(); 34 | char prev = ' '; 35 | 36 | int sum = 0; 37 | 38 | int newPrev = 0; 39 | for (int i = A.length() - 1; i >= 0; i--) { 40 | char c = A.charAt(i); 41 | 42 | if (prev != ' ') { 43 | // checking current Number greater then previous or not 44 | newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev; 45 | } 46 | 47 | int currentNum = map.get(c); 48 | 49 | // if current number greater then prev max previous then add 50 | if (currentNum >= newPrev) { 51 | sum += currentNum; 52 | } else { 53 | // subtract upcoming number until upcoming number not greater then prev max 54 | sum -= currentNum; 55 | } 56 | 57 | prev = c; 58 | } 59 | 60 | return sum; 61 | } 62 | 63 | public static void main(String[] args) { 64 | int sum = romanToInt("MDCCCIV"); 65 | System.out.println(sum); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Conversions/TurkishToLatinConversion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts turkish character to latin character 7 | * 8 | * @author Özgün Gökşenli 9 | */ 10 | public class TurkishToLatinConversion { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the string: "); 20 | String b = sc.next(); 21 | System.out.println("Converted: " + convertTurkishToLatin(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a turkish character to latin character. 27 | * 28 | * @param param String paramter 29 | * @return String 30 | */ 31 | public static String convertTurkishToLatin(String param) { 32 | char[] turkishChars 33 | = new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E}; 34 | char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'}; 35 | for (int i = 0; i < turkishChars.length; i++) { 36 | param 37 | = param.replaceAll( 38 | new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]})); 39 | } 40 | return param; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Misc/ColorContrastRatio.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.awt.Color; 4 | 5 | /** 6 | * @brief A Java implementation of the offcial W3 documented procedure to 7 | * calculate contrast ratio between colors on the web. This is used to calculate 8 | * the readability of a foreground color on top of a background color. 9 | * @since 2020-10-15 10 | * @see [Color Contrast 11 | * Ratio](https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure) 12 | * @author [Seth Falco](https://github.com/SethFalco) 13 | */ 14 | public class ColorContrastRatio { 15 | 16 | /** 17 | * @brief Calculates the contrast ratio between two given colors. 18 | * @param a Any color, used to get the red, green, and blue values. 19 | * @param b Another color, which will be compared against the first color. 20 | * @return The contrast ratio between the two colors. 21 | */ 22 | public double getContrastRatio(Color a, Color b) { 23 | final double aColorLuminance = getRelativeLuminance(a); 24 | final double bColorLuminance = getRelativeLuminance(b); 25 | 26 | if (aColorLuminance > bColorLuminance) { 27 | return (aColorLuminance + 0.05) / (bColorLuminance + 0.05); 28 | } 29 | 30 | return (bColorLuminance + 0.05) / (aColorLuminance + 0.05); 31 | } 32 | 33 | /** 34 | * @brief Calculates the relative luminance of a given color. 35 | * @param color Any color, used to get the red, green, and blue values. 36 | * @return The relative luminance of the color. 37 | * @see [More info on relative 38 | * luminance.](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef) 39 | */ 40 | public double getRelativeLuminance(Color color) { 41 | final double red = getColor(color.getRed()); 42 | final double green = getColor(color.getGreen()); 43 | final double blue = getColor(color.getBlue()); 44 | 45 | return 0.2126 * red + 0.7152 * green + 0.0722 * blue; 46 | } 47 | 48 | /** 49 | * @brief Calculates the final value for a color to be used in the relative 50 | * luminance formula as described in step 1. 51 | * @param color8Bit 8-bit representation of a color component value. 52 | * @return Value for the provided color component to be used in the relative 53 | * luminance formula. 54 | */ 55 | public double getColor(int color8Bit) { 56 | final double sRgb = getColorSRgb(color8Bit); 57 | return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4); 58 | } 59 | 60 | /** 61 | * @brief Calculates the Color sRGB value as denoted in step 1 of the 62 | * procedure document. 63 | * @param color8Bit 8-bit representation of a color component value. 64 | * @return A percentile value of the color component. 65 | */ 66 | private double getColorSRgb(double color8Bit) { 67 | return color8Bit / 255.0; 68 | } 69 | 70 | /** 71 | * You can check this example against another open-source implementation 72 | * available on GitHub. 73 | * 74 | * @see [Online Contrast 75 | * Ratio](https://contrast-ratio.com/#rgb%28226%2C%20229%2C%20248-on-rgb%2823%2C%20103%2C%20154%29) 76 | * @see [GitHub Repository for Online Contrast 77 | * Ratio](https://github.com/LeaVerou/contrast-ratio) 78 | */ 79 | private static void test() { 80 | final ColorContrastRatio algImpl = new ColorContrastRatio(); 81 | 82 | final Color black = Color.BLACK; 83 | final double blackLuminance = algImpl.getRelativeLuminance(black); 84 | assert blackLuminance == 0 : "Test 1 Failed - Incorrect relative luminance."; 85 | 86 | final Color white = Color.WHITE; 87 | final double whiteLuminance = algImpl.getRelativeLuminance(white); 88 | assert whiteLuminance == 1 : "Test 2 Failed - Incorrect relative luminance."; 89 | 90 | final double highestColorRatio = algImpl.getContrastRatio(black, white); 91 | assert highestColorRatio == 21 : "Test 3 Failed - Incorrect contrast ratio."; 92 | 93 | final Color foreground = new Color(23, 103, 154); 94 | final double foregroundLuminance = algImpl.getRelativeLuminance(foreground); 95 | assert foregroundLuminance == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; 96 | 97 | final Color background = new Color(226, 229, 248); 98 | final double backgroundLuminance = algImpl.getRelativeLuminance(background); 99 | assert backgroundLuminance == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance."; 100 | 101 | final double contrastRatio = algImpl.getContrastRatio(foreground, background); 102 | assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; 103 | } 104 | 105 | public static void main(String args[]) { 106 | test(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Misc/InverseOfMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Scanner; 4 | 5 | /* 6 | * Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix 7 | * 8 | * Here we use gauss elimination method to find the inverse of a given matrix. 9 | * To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination 10 | * 11 | * We can also find the inverse of a matrix 12 | */ 13 | public class InverseOfMatrix { 14 | 15 | public static void main(String argv[]) { 16 | Scanner input = new Scanner(System.in); 17 | System.out.println("Enter the matrix size (Square matrix only): "); 18 | int n = input.nextInt(); 19 | double a[][] = new double[n][n]; 20 | System.out.println("Enter the elements of matrix: "); 21 | for (int i = 0; i < n; i++) { 22 | for (int j = 0; j < n; j++) { 23 | a[i][j] = input.nextDouble(); 24 | } 25 | } 26 | 27 | double d[][] = invert(a); 28 | System.out.println(); 29 | System.out.println("The inverse is: "); 30 | for (int i = 0; i < n; ++i) { 31 | for (int j = 0; j < n; ++j) { 32 | System.out.print(d[i][j] + " "); 33 | } 34 | System.out.println(); 35 | } 36 | input.close(); 37 | } 38 | 39 | public static double[][] invert(double a[][]) { 40 | int n = a.length; 41 | double x[][] = new double[n][n]; 42 | double b[][] = new double[n][n]; 43 | int index[] = new int[n]; 44 | for (int i = 0; i < n; ++i) { 45 | b[i][i] = 1; 46 | } 47 | 48 | // Transform the matrix into an upper triangle 49 | gaussian(a, index); 50 | 51 | // Update the matrix b[i][j] with the ratios stored 52 | for (int i = 0; i < n - 1; ++i) { 53 | for (int j = i + 1; j < n; ++j) { 54 | for (int k = 0; k < n; ++k) { 55 | b[index[j]][k] 56 | -= a[index[j]][i] * b[index[i]][k]; 57 | } 58 | } 59 | } 60 | 61 | // Perform backward substitutions 62 | for (int i = 0; i < n; ++i) { 63 | x[n - 1][i] = b[index[n - 1]][i] / a[index[n - 1]][n - 1]; 64 | for (int j = n - 2; j >= 0; --j) { 65 | x[j][i] = b[index[j]][i]; 66 | for (int k = j + 1; k < n; ++k) { 67 | x[j][i] -= a[index[j]][k] * x[k][i]; 68 | } 69 | x[j][i] /= a[index[j]][j]; 70 | } 71 | } 72 | return x; 73 | } 74 | 75 | // Method to carry out the partial-pivoting Gaussian 76 | // elimination. Here index[] stores pivoting order. 77 | public static void gaussian(double a[][], int index[]) { 78 | int n = index.length; 79 | double c[] = new double[n]; 80 | 81 | // Initialize the index 82 | for (int i = 0; i < n; ++i) { 83 | index[i] = i; 84 | } 85 | 86 | // Find the rescaling factors, one from each row 87 | for (int i = 0; i < n; ++i) { 88 | double c1 = 0; 89 | for (int j = 0; j < n; ++j) { 90 | double c0 = Math.abs(a[i][j]); 91 | if (c0 > c1) { 92 | c1 = c0; 93 | } 94 | } 95 | c[i] = c1; 96 | } 97 | 98 | // Search the pivoting element from each column 99 | int k = 0; 100 | for (int j = 0; j < n - 1; ++j) { 101 | double pi1 = 0; 102 | for (int i = j; i < n; ++i) { 103 | double pi0 = Math.abs(a[index[i]][j]); 104 | pi0 /= c[index[i]]; 105 | if (pi0 > pi1) { 106 | pi1 = pi0; 107 | k = i; 108 | } 109 | } 110 | // Interchange rows according to the pivoting order 111 | int itmp = index[j]; 112 | index[j] = index[k]; 113 | index[k] = itmp; 114 | for (int i = j + 1; i < n; ++i) { 115 | double pj = a[index[i]][j] / a[index[j]][j]; 116 | 117 | // Record pivoting ratios below the diagonal 118 | a[index[i]][j] = pj; 119 | 120 | // Modify other elements accordingly 121 | for (int l = j + 1; l < n; ++l) { 122 | a[index[i]][l] -= pj * a[index[j]][l]; 123 | } 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /Misc/MedianOfRunningArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author shrutisheoran 8 | */ 9 | public class MedianOfRunningArray { 10 | 11 | private PriorityQueue p1; 12 | private PriorityQueue p2; 13 | 14 | // Constructor 15 | public MedianOfRunningArray() { 16 | this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap 17 | this.p2 = new PriorityQueue<>(); // Min Heap 18 | } 19 | 20 | /* 21 | Inserting lower half of array to max Heap 22 | and upper half to min heap 23 | */ 24 | public void insert(Integer e) { 25 | p2.add(e); 26 | if (p2.size() - p1.size() > 1) { 27 | p1.add(p2.remove()); 28 | } 29 | } 30 | 31 | /* 32 | Returns median at any given point 33 | */ 34 | public Integer median() { 35 | if (p1.size() == p2.size()) { 36 | return (p1.peek() + p2.peek()) / 2; 37 | } 38 | return p1.size() > p2.size() ? p1.peek() : p2.peek(); 39 | } 40 | 41 | public static void main(String[] args) { 42 | /* 43 | Testing the median function 44 | */ 45 | 46 | MedianOfRunningArray p = new MedianOfRunningArray(); 47 | int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; 48 | for (int i = 0; i < 9; i++) { 49 | p.insert(arr[i]); 50 | System.out.print(p.median() + " "); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Misc/PalindromePrime.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PalindromePrime { 6 | 7 | public static void main(String[] args) { // Main funtion 8 | Scanner in = new Scanner(System.in); 9 | System.out.println("Enter the quantity of First Palindromic Primes you want"); 10 | int n = in.nextInt(); // Input of how many first palindromic prime we want 11 | functioning(n); // calling function - functioning 12 | in.close(); 13 | } 14 | 15 | public static boolean prime(int num) { // checking if number is prime or not 16 | for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { 17 | if (num % divisor == 0) { 18 | return false; // false if not prime 19 | } 20 | } 21 | return true; // True if prime 22 | } 23 | 24 | public static int reverse(int n) { // Returns the reverse of the number 25 | int reverse = 0; 26 | while (n != 0) { 27 | reverse *= 10; 28 | reverse += n % 10; 29 | n /= 10; 30 | } 31 | return reverse; 32 | } 33 | 34 | public static void functioning(int y) { 35 | if (y == 0) { 36 | return; 37 | } 38 | System.out.print(2 + "\n"); // print the first Palindromic Prime 39 | int count = 1; 40 | int num = 3; 41 | while (count < y) { 42 | if (num == reverse(num) && prime(num)) { // number is prime and it's reverse is same 43 | count++; // counts check when to terminate while loop 44 | System.out.print(num + "\n"); // print the Palindromic Prime 45 | } 46 | num += 2; // inrease iterator value by two 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Misc/PalindromeSinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Stack; 4 | import com.thealgorithms.datastructures.lists.SinglyLinkedList; 5 | 6 | /** 7 | * A simple way of knowing if a singly linked list is palindrome is to push all 8 | * the values into a Stack and then compare the list to popped vales from the 9 | * Stack. 10 | * 11 | * See more: 12 | * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ 13 | */ 14 | public class PalindromeSinglyLinkedList { 15 | 16 | public static void main(String[] args) { 17 | SinglyLinkedList linkedList = new SinglyLinkedList(); 18 | 19 | linkedList.insertHead(3); 20 | linkedList.insertNth(2, 1); 21 | linkedList.insertNth(1, 2); 22 | linkedList.insertNth(2, 3); 23 | linkedList.insertNth(3, 4); 24 | 25 | if (isPalindrome(linkedList)) { 26 | System.out.println("It's a palindrome list"); 27 | } else { 28 | System.out.println("It's NOT a palindrome list"); 29 | } 30 | } 31 | 32 | public static boolean isPalindrome(SinglyLinkedList linkedList) { 33 | boolean ret = true; 34 | Stack linkedListValues = new Stack<>(); 35 | 36 | for (int i = 0; i < linkedList.size(); i++) { 37 | linkedListValues.push(linkedList.getNth(i)); 38 | } 39 | 40 | for (int i = 0; i < linkedList.size(); i++) { 41 | if (linkedList.getNth(i) != linkedListValues.pop()) { 42 | ret = false; 43 | break; 44 | } 45 | } 46 | 47 | return ret; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Misc/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Misc/RangeInSortedArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | 5 | public class RangeInSortedArray { 6 | 7 | public static void main(String[] args) { 8 | // Testcases 9 | assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 3), new int[]{2, 4}); 10 | assert Arrays.equals(sortedRange(new int[]{1, 2, 3, 3, 3, 4, 5}, 4), new int[]{5, 5}); 11 | assert Arrays.equals(sortedRange(new int[]{0, 1, 2}, 3), new int[]{-1, -1}); 12 | } 13 | 14 | // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums' 15 | // Gives [-1, -1] in case element doesn't exist in array 16 | public static int[] sortedRange(int[] nums, int key) { 17 | int[] range = new int[]{-1, -1}; 18 | alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true); 19 | alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false); 20 | return range; 21 | } 22 | 23 | // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of 24 | // 'key' 25 | public static void alteredBinSearch( 26 | int[] nums, int key, int left, int right, int[] range, boolean goLeft) { 27 | if (left > right) { 28 | return; 29 | } 30 | int mid = (left + right) / 2; 31 | if (nums[mid] > key) { 32 | alteredBinSearch(nums, key, left, mid - 1, range, goLeft); 33 | } else if (nums[mid] < key) { 34 | alteredBinSearch(nums, key, mid + 1, right, range, goLeft); 35 | } else { 36 | if (goLeft) { 37 | if (mid == 0 || nums[mid - 1] != key) { 38 | range[0] = mid; 39 | } else { 40 | alteredBinSearch(nums, key, left, mid - 1, range, goLeft); 41 | } 42 | } else { 43 | if (mid == nums.length - 1 || nums[mid + 1] != key) { 44 | range[1] = mid; 45 | } else { 46 | alteredBinSearch(nums, key, mid + 1, right, range, goLeft); 47 | } 48 | } 49 | } 50 | } 51 | 52 | // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of 53 | // 'key' 54 | public static void alteredBinSearchIter( 55 | int[] nums, int key, int left, int right, int[] range, boolean goLeft) { 56 | while (left <= right) { 57 | int mid = (left + right) / 2; 58 | if (nums[mid] > key) { 59 | right = mid - 1; 60 | } else if (nums[mid] < key) { 61 | left = mid + 1; 62 | } else { 63 | if (goLeft) { 64 | if (mid == 0 || nums[mid - 1] != key) { 65 | range[0] = mid; 66 | return; 67 | } else { 68 | right = mid - 1; 69 | } 70 | } else { 71 | if (mid == nums.length - 1 || nums[mid + 1] != key) { 72 | range[1] = mid; 73 | return; 74 | } else { 75 | left = mid + 1; 76 | } 77 | } 78 | } 79 | } 80 | } 81 | 82 | public static int getCountLessThan(int[] nums, int key) { 83 | return getLessThan(nums, key, 0, nums.length - 1); 84 | } 85 | 86 | public static int getLessThan(int[] nums, int key, int left, int right) { 87 | int count = 0; 88 | while (left <= right) { 89 | int mid = (left + right) / 2; 90 | if (nums[mid] > key) { 91 | right = mid - 1; 92 | } else if (nums[mid] <= key) { 93 | count = mid + 1; // Atleast mid+1 elements exist which are <= key 94 | left = mid + 1; 95 | } 96 | } 97 | return count; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Misc/Sort012D.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * The array is divided into four sections: a[1..Lo-1] zeroes a[Lo..Mid-1] ones 7 | * a[Mid..Hi] unknown a[Hi+1..N] twos If array [mid] =0, then swap array [mid] 8 | * with array [low] and increment both pointers once. If array [mid] = 1, then 9 | * no swapping is required. Increment mid pointer once. If array [mid] = 2, then 10 | * we swap array [mid] with array [high] and decrement the high pointer once. 11 | * For more information on the Dutch national flag algorithm refer 12 | * https://en.wikipedia.org/wiki/Dutch_national_flag_problem 13 | */ 14 | public class Sort012D { 15 | 16 | public static void main(String args[]) { 17 | Scanner np = new Scanner(System.in); 18 | int n = np.nextInt(); 19 | int a[] = new int[n]; 20 | for (int i = 0; i < n; i++) { 21 | a[i] = np.nextInt(); 22 | } 23 | sort012(a); 24 | } 25 | 26 | public static void sort012(int[] a) { 27 | int l = 0; 28 | int h = a.length - 1; 29 | int mid = 0; 30 | int temp; 31 | while (mid <= h) { 32 | switch (a[mid]) { 33 | case 0: { 34 | temp = a[l]; 35 | a[l] = a[mid]; 36 | a[mid] = temp; 37 | l++; 38 | mid++; 39 | break; 40 | } 41 | case 1: 42 | mid++; 43 | break; 44 | case 2: { 45 | temp = a[mid]; 46 | a[mid] = a[h]; 47 | a[h] = temp; 48 | h--; 49 | break; 50 | } 51 | } 52 | } 53 | System.out.println("the Sorted array is "); 54 | for (int i = 0; i < a.length; i++) { 55 | System.out.print(+a[i] + " "); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Misc/Sparcity.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | 5 | /* 6 | *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). 7 | *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. 8 | * 9 | * @author Ojasva Jain 10 | */ 11 | 12 | class Sparcity { 13 | 14 | /* 15 | * @return Sparcity of matrix 16 | * 17 | * where sparcity = number of zeroes/total elements in matrix 18 | * 19 | */ 20 | static double sparcity(double[][] mat) { 21 | int zero = 0; 22 | //Traversing the matrix to count number of zeroes 23 | for (int i = 0; i < mat.length; i++) { 24 | for (int j = 0; j < mat[i].length; j++) { 25 | if (mat[i][j] == 0) { 26 | zero++; 27 | } 28 | } 29 | } 30 | //return sparcity 31 | return ((double) zero / (mat.length * mat[1].length)); 32 | } 33 | 34 | //Driver method 35 | public static void main(String[] args) { 36 | Scanner in = new Scanner(System.in); 37 | System.out.println("Enter number of rows in matrix: "); 38 | int n = in.nextInt(); 39 | System.out.println("Enter number of Columns in matrix: "); 40 | int m = in.nextInt(); 41 | 42 | System.out.println("Enter Matrix elements: "); 43 | double[][] mat = new double[n][m]; 44 | for (int i = 0; i < n; i++) { 45 | for (int j = 0; j < m; j++) { 46 | mat[i][j] = in.nextDouble(); 47 | } 48 | } 49 | System.out.println("Sparcity of matrix is: " + sparcity(mat)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Misc/ThreeSumProblem.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | 5 | public class ThreeSumProblem { 6 | 7 | public static void main(String args[]) { 8 | Scanner scan = new Scanner(System.in); 9 | System.out.print("Enter the target sum "); 10 | int ts = scan.nextInt(); 11 | System.out.print("Enter the number of elements in the array "); 12 | int n = scan.nextInt(); 13 | System.out.println("Enter all your array elements:"); 14 | int arr[] = new int[n]; 15 | for (int i = 0; i < n; i++) { 16 | arr[i] = scan.nextInt(); 17 | } 18 | ThreeSumProblem th = new ThreeSumProblem(); 19 | System.out.println("Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n"); 20 | System.out.println("Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n"); 21 | System.out.println("Hashmap Approach\n" + (th.Hashmap(arr, ts))); 22 | 23 | } 24 | 25 | public List> BruteForce(int[] nums, int target) { 26 | List> arr = new ArrayList>(); 27 | 28 | for (int i = 0; i < nums.length; i++) { 29 | for (int j = i + 1; j < nums.length; j++) { 30 | for (int k = j + 1; k < nums.length; k++) { 31 | if (nums[i] + nums[j] + nums[k] == target) { 32 | List temp = new ArrayList<>(); 33 | temp.add(nums[i]); 34 | temp.add(nums[j]); 35 | temp.add(nums[k]); 36 | Collections.sort(temp); 37 | arr.add(temp); 38 | } 39 | 40 | } 41 | } 42 | } 43 | arr = new ArrayList>(new LinkedHashSet>(arr)); 44 | return arr; 45 | } 46 | 47 | public List> TwoPointer(int[] nums, int target) { 48 | Arrays.sort(nums); 49 | List> arr = new ArrayList>(); 50 | int start = 0; 51 | int end = 0; 52 | int i = 0; 53 | while (i < nums.length - 1) { 54 | start = i + 1; 55 | end = nums.length - 1; 56 | while (start < end) { 57 | if (nums[start] + nums[end] + nums[i] == target) { 58 | List temp = new ArrayList<>(); 59 | temp.add(nums[i]); 60 | temp.add(nums[start]); 61 | temp.add(nums[end]); 62 | arr.add(temp); 63 | start++; 64 | end--; 65 | } else if (nums[start] + nums[end] + nums[i] < target) { 66 | start += 1; 67 | } else { 68 | end -= 1; 69 | } 70 | 71 | } 72 | i++; 73 | } 74 | Set> set = new LinkedHashSet>(arr); 75 | return new ArrayList>(set); 76 | } 77 | 78 | public List> Hashmap(int[] nums, int target) { 79 | Arrays.sort(nums); 80 | Set> ts = new HashSet(); 81 | HashMap hm = new HashMap<>(); 82 | 83 | for (int i = 0; i < nums.length; i++) { 84 | hm.put(nums[i], i); 85 | } 86 | 87 | for (int i = 0; i < nums.length; i++) { 88 | for (int j = i + 1; j < nums.length; j++) { 89 | int t = target - nums[i] - nums[j]; 90 | if (hm.containsKey(t) && hm.get(t) > j) { 91 | List temp = new ArrayList<>(); 92 | temp.add(nums[i]); 93 | temp.add(nums[j]); 94 | temp.add(t); 95 | ts.add(temp); 96 | } 97 | } 98 | } 99 | return new ArrayList(ts); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /Misc/TwoSumProblem.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.*; 4 | import java.util.stream.Collectors; 5 | 6 | public class TwoSumProblem { 7 | 8 | public static void main(String args[]) { 9 | Scanner scan = new Scanner(System.in); 10 | System.out.print("Enter the target sum "); 11 | int ts = scan.nextInt(); 12 | System.out.print("Enter the number of elements in the array "); 13 | int n = scan.nextInt(); 14 | System.out.println("Enter all your array elements:"); 15 | int arr[] = new int[n]; 16 | for (int i = 0; i < n; i++) { 17 | arr[i] = scan.nextInt(); 18 | } 19 | TwoSumProblem t = new TwoSumProblem(); 20 | System.out.println("Brute Force Approach\n" + Arrays.toString(t.BruteForce(arr, ts)) + "\n"); 21 | System.out.println("Two Pointer Approach\n" + Arrays.toString(t.TwoPointer(arr, ts)) + "\n"); 22 | System.out.println("Hashmap Approach\n" + Arrays.toString(t.HashMap(arr, ts))); 23 | 24 | } 25 | 26 | public int[] BruteForce(int[] nums, int target) { 27 | //Brute Force Approach 28 | int ans[] = new int[2]; 29 | for (int i = 0; i < nums.length; i++) { 30 | for (int j = i + 1; j < nums.length; j++) { 31 | if (nums[i] + nums[j] == target) { 32 | ans[0] = i; 33 | ans[1] = j; 34 | 35 | break; 36 | } 37 | 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | 44 | public int[] TwoPointer(int[] nums, int target) { 45 | // HashMap Approach 46 | int ans[] = new int[2]; 47 | HashMap hm = new HashMap(); 48 | for (int i = 0; i < nums.length; i++) { 49 | hm.put(i, nums[i]); 50 | } 51 | HashMap temp 52 | = hm.entrySet() 53 | .stream() 54 | .sorted((i1, i2) 55 | -> i1.getValue().compareTo( 56 | i2.getValue())) 57 | .collect(Collectors.toMap( 58 | Map.Entry::getKey, 59 | Map.Entry::getValue, 60 | (e1, e2) -> e1, LinkedHashMap::new)); 61 | 62 | int start = 0; 63 | int end = nums.length - 1; 64 | while (start < end) { 65 | int currSum = (Integer) temp.values().toArray()[start] + (Integer) temp.values().toArray()[end]; 66 | 67 | if (currSum == target) { 68 | ans[0] = (Integer) temp.keySet().toArray()[start]; 69 | ans[1] = (Integer) temp.keySet().toArray()[end]; 70 | break; 71 | } else if (currSum > target) { 72 | end -= 1; 73 | } else if (currSum < target) { 74 | start += 1; 75 | } 76 | 77 | } 78 | return ans; 79 | 80 | } 81 | 82 | public int[] HashMap(int[] nums, int target) { 83 | //Using Hashmaps 84 | int ans[] = new int[2]; 85 | HashMap hm = new HashMap(); 86 | for (int i = 0; i < nums.length; i++) { 87 | hm.put(nums[i], i); 88 | } 89 | for (int i = 0; i < nums.length; i++) { 90 | int t = target - nums[i]; 91 | if (hm.containsKey(t) && hm.get(t) != i) { 92 | ans[0] = i; 93 | ans[1] = hm.get(t); 94 | break; 95 | } 96 | } 97 | 98 | return ans; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /Misc/matrixTranspose.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * 7 | * 8 | *

Find the Transpose of Matrix!

9 | * 10 | * Simply take input from the user and print the matrix before the transpose and 11 | * after the transpose. 12 | * 13 | *

14 | * Note: Giving proper comments in your program makes it more user 15 | * friendly and it is assumed as a high quality code. 16 | * 17 | * @author Rajat-Jain29 18 | * @version 11.0.9 19 | * @since 2014-03-31 20 | */ 21 | public class matrixTranspose { 22 | 23 | public static void main(String[] args) { 24 | /* 25 | * This is the main method 26 | * 27 | * @param args Unused. 28 | * 29 | * @return Nothing. 30 | */ 31 | Scanner sc = new Scanner(System.in); 32 | int i, j, row, column; 33 | System.out.println("Enter the number of rows in the 2D matrix:"); 34 | 35 | /* 36 | * Take input from user for how many rows to be print 37 | */ 38 | row = sc.nextInt(); 39 | 40 | System.out.println("Enter the number of columns in the 2D matrix:"); 41 | 42 | /* 43 | * Take input from user for how many coloumn to be print 44 | */ 45 | column = sc.nextInt(); 46 | int[][] arr = new int[row][column]; 47 | System.out.println("Enter the elements"); 48 | for (i = 0; i < row; i++) { 49 | for (j = 0; j < column; j++) { 50 | arr[i][j] = sc.nextInt(); 51 | } 52 | } 53 | 54 | /* 55 | * Print matrix before the Transpose in proper way 56 | */ 57 | System.out.println("The matrix is:"); 58 | for (i = 0; i < row; i++) { 59 | for (j = 0; j < column; j++) { 60 | System.out.print(arr[i][j] + "\t"); 61 | } 62 | System.out.print("\n"); 63 | } 64 | 65 | /* 66 | * Print matrix after the tranpose in proper way Transpose means Interchanging 67 | * of rows wth column so we interchange the rows in next loop Thus at last 68 | * matrix of transpose is obtained through user input... 69 | */ 70 | System.out.println("The Transpose of the given matrix is:"); 71 | for (i = 0; i < column; i++) { 72 | for (j = 0; j < row; j++) { 73 | System.out.print(arr[j][i] + "\t"); 74 | } 75 | System.out.print("\n"); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Others/ArrayLeftRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /* 4 | * A left rotation operation on an array 5 | * shifts each of the array's elements 6 | * given integer n unit to the left. 7 | * 8 | * @author sangin-lee 9 | */ 10 | 11 | public class ArrayLeftRotation { 12 | 13 | /* 14 | * Returns the result of left rotation of given array arr and integer n 15 | * 16 | * @param arr : int[] given array 17 | * 18 | * @param n : int given integer 19 | * 20 | * @return : int[] result of left rotation 21 | */ 22 | public static int[] rotateLeft(int[] arr, int n) { 23 | int size = arr.length; 24 | int[] dst = new int[size]; 25 | n = n % size; 26 | for(int i = 0; i < size; i++) { 27 | dst[i] = arr[n]; 28 | n = (n + 1) % size; 29 | } 30 | return dst; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Others/BFPRT.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * BFPRT algorithm. 7 | */ 8 | public class BFPRT { 9 | 10 | public static int[] getMinKNumsByBFPRT(int[] arr, int k) { 11 | if (k < 1 || k > arr.length) { 12 | return null; 13 | } 14 | int minKth = getMinKthByBFPRT(arr, k); 15 | int[] res = new int[k]; 16 | int index = 0; 17 | for (int i = 0; i < arr.length; i++) { 18 | if (arr[i] < minKth) { 19 | res[index++] = arr[i]; 20 | } 21 | } 22 | for (; index != res.length; index++) { 23 | res[index] = minKth; 24 | } 25 | return res; 26 | } 27 | 28 | public static int getMinKthByBFPRT(int[] arr, int k) { 29 | int[] copyArr = copyArray(arr); 30 | return bfprt(copyArr, 0, copyArr.length - 1, k - 1); 31 | } 32 | 33 | public static int[] copyArray(int[] arr) { 34 | int[] copyArr = new int[arr.length]; 35 | for (int i = 0; i < arr.length; i++) { 36 | copyArr[i] = arr[i]; 37 | } 38 | return copyArr; 39 | } 40 | 41 | public static int bfprt(int[] arr, int begin, int end, int i) { 42 | if (begin == end) { 43 | return arr[begin]; 44 | } 45 | int pivot = medianOfMedians(arr, begin, end); 46 | int[] pivotRange = partition(arr, begin, end, pivot); 47 | if (i >= pivotRange[0] && i <= pivotRange[1]) { 48 | return arr[i]; 49 | } else if (i < pivotRange[0]) { 50 | return bfprt(arr, begin, pivotRange[0] - 1, i); 51 | } else { 52 | return bfprt(arr, pivotRange[1] + 1, end, i); 53 | } 54 | } 55 | 56 | /** 57 | * wikipedia: https://en.wikipedia.org/wiki/Median_of_medians . 58 | * 59 | * @param arr an array. 60 | * @param begin begin num. 61 | * @param end end num. 62 | * @return median of medians. 63 | */ 64 | public static int medianOfMedians(int[] arr, int begin, int end) { 65 | int num = end - begin + 1; 66 | int offset = num % 5 == 0 ? 0 : 1; 67 | int[] mArr = new int[num / 5 + offset]; 68 | for (int i = 0; i < mArr.length; i++) { 69 | mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); 70 | } 71 | return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); 72 | } 73 | 74 | public static void swap(int[] arr, int i, int j) { 75 | int swap = arr[i]; 76 | arr[i] = arr[j]; 77 | arr[j] = swap; 78 | } 79 | 80 | public static int[] partition(int[] arr, int begin, int end, int num) { 81 | int small = begin - 1; 82 | int cur = begin; 83 | int big = end + 1; 84 | while (cur != big) { 85 | if (arr[cur] < num) { 86 | swap(arr, ++small, cur++); 87 | } else if (arr[cur] > num) { 88 | swap(arr, --big, cur); 89 | } else { 90 | cur++; 91 | } 92 | } 93 | int[] pivotRange = new int[2]; 94 | pivotRange[0] = small + 1; 95 | pivotRange[1] = big - 1; 96 | return pivotRange; 97 | } 98 | 99 | public static int getMedian(int[] arr, int begin, int end) { 100 | insertionSort(arr, begin, end); 101 | int sum = begin + end; 102 | int mid = sum / 2 + (sum % 2); 103 | return arr[mid]; 104 | } 105 | 106 | public static void insertionSort(int[] arr, int begin, int end) { 107 | if (arr == null || arr.length < 2) { 108 | return; 109 | } 110 | for (int i = begin + 1; i != end + 1; i++) { 111 | for (int j = i; j != begin; j--) { 112 | if (arr[j - 1] > arr[j]) { 113 | swap(arr, j - 1, j); 114 | } else { 115 | break; 116 | } 117 | } 118 | } 119 | } 120 | 121 | public static void main(String[] args) { 122 | int[] arr = {11, 9, 1, 3, 9, 2, 2, 5, 6, 5, 3, 5, 9, 7, 2, 5, 5, 1, 9}; 123 | int[] minK = getMinKNumsByBFPRT(arr, 5); 124 | System.out.println(Arrays.toString(minK)); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /Others/BoyerMoore.java: -------------------------------------------------------------------------------- 1 | /* this Code is the illustration of Boyer moore's voting algorithm to 2 | find the majority element is an array that appears more than n/2 times in an array 3 | where "n" is the length of the array. 4 | For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm 5 | */ 6 | package com.thealgorithms.others; 7 | 8 | import java.util.*; 9 | 10 | public class BoyerMoore { 11 | 12 | public static int findmajor(int[] a) { 13 | int count = 0; 14 | int cand = -1; 15 | for (int i = 0; i < a.length; i++) { 16 | if (count == 0) { 17 | cand = a[i]; 18 | count = 1; 19 | } else { 20 | if (a[i] == cand) { 21 | count++; 22 | } else { 23 | count--; 24 | } 25 | } 26 | } 27 | for (int i = 0; i < a.length; i++) { 28 | if (a[i] == cand) { 29 | count++; 30 | } 31 | } 32 | if (count > (a.length / 2)) { 33 | return cand; 34 | } 35 | return -1; 36 | } 37 | 38 | public static void main(String args[]) { 39 | Scanner input = new Scanner(System.in); 40 | int n = input.nextInt(); 41 | int a[] = new int[n]; 42 | for (int i = 0; i < n; i++) { 43 | a[i] = input.nextInt(); 44 | } 45 | System.out.println("the majority element is " + findmajor(a)); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Others/BrianKernighanAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author Nishita Aggarwal 7 | *

8 | * Brian Kernighan’s Algorithm 9 | *

10 | * algorithm to count the number of set bits in a given number 11 | *

12 | * Subtraction of 1 from a number toggles all the bits (from right to left) till 13 | * the rightmost set bit(including the rightmost set bit). So if we subtract a 14 | * number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the 15 | * rightmost set bit. 16 | *

17 | * If we do n & (n-1) in a loop and count the no of times loop executes we get 18 | * the set bit count. 19 | *

20 | *

21 | * Time Complexity: O(logn) 22 | */ 23 | public class BrianKernighanAlgorithm { 24 | 25 | /** 26 | * @param num: number in which we count the set bits 27 | * @return int: Number of set bits 28 | */ 29 | static int countSetBits(int num) { 30 | int cnt = 0; 31 | while (num != 0) { 32 | num = num & (num - 1); 33 | cnt++; 34 | } 35 | return cnt; 36 | } 37 | 38 | /** 39 | * @param args : command line arguments 40 | */ 41 | public static void main(String args[]) { 42 | Scanner sc = new Scanner(System.in); 43 | int num = sc.nextInt(); 44 | int setBitCount = countSetBits(num); 45 | System.out.println(setBitCount); 46 | sc.close(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Others/CRC32.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.BitSet; 4 | 5 | /** 6 | * Generates a crc32 checksum for a given string or byte array 7 | */ 8 | public class CRC32 { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(Integer.toHexString(crc32("Hello World"))); 12 | } 13 | 14 | public static int crc32(String str) { 15 | return crc32(str.getBytes()); 16 | } 17 | 18 | public static int crc32(byte[] data) { 19 | BitSet bitSet = BitSet.valueOf(data); 20 | int crc32 = 0xFFFFFFFF; // initial value 21 | for (int i = 0; i < data.length * 8; i++) { 22 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { 23 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial 24 | } else { 25 | crc32 = (crc32 << 1); 26 | } 27 | } 28 | crc32 = Integer.reverse(crc32); // result reflect 29 | return crc32 ^ 0xFFFFFFFF; // final xor value 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Others/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Enter your text: "); 10 | String str = input.nextLine(); 11 | input.close(); 12 | System.out.println("There are " + CountCharacters(str) + " characters."); 13 | } 14 | 15 | /** 16 | * Count non space character in string 17 | * 18 | * @param str String to count the characters 19 | * @return number of character in the specified string 20 | */ 21 | private static int CountCharacters(String str) { 22 | return str.replaceAll("\\s", "").length(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Others/CountWords.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * You enter a string into this program, and it will return how many words were 7 | * in that particular string 8 | * 9 | * @author Marcus 10 | */ 11 | public class CountWords { 12 | 13 | public static void main(String[] args) { 14 | Scanner input = new Scanner(System.in); 15 | System.out.println("Enter your text: "); 16 | String str = input.nextLine(); 17 | 18 | System.out.println("Your text has " + wordCount(str) + " word(s)"); 19 | System.out.println("Your text has " + secondaryWordCount(str) + " word(s)"); 20 | input.close(); 21 | } 22 | 23 | private static int wordCount(String s) { 24 | if (s == null || s.isEmpty()) { 25 | return 0; 26 | } 27 | return s.trim().split("[\\s]+").length; 28 | } 29 | 30 | /** 31 | * counts the number of words in a sentence but ignores all potential 32 | * non-alphanumeric characters that do not represent a word. runs in O(n) 33 | * where n is the length of s 34 | * 35 | * @param s String: sentence with word(s) 36 | * @return int: number of words 37 | */ 38 | private static int secondaryWordCount(String s) { 39 | if (s == null || s.isEmpty()) { 40 | return 0; 41 | } 42 | StringBuilder sb = new StringBuilder(); 43 | for (char c : s.toCharArray()) { 44 | if (Character.isLetter(c) || Character.isDigit(c)) { 45 | sb.append(c); 46 | } 47 | } 48 | s = sb.toString(); 49 | return s.trim().split("[\\s]+").length; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Others/Damm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Damm algorithm is a check digit algorithm that detects all single-digit 7 | * errors and all adjacent transposition errors. It was presented by H. Michael 8 | * Damm in 2004. Essential part of the algorithm is a quasigroup of order 10 9 | * (i.e. having a 10 × 10 Latin square as the body of its operation table) with 10 | * the special feature of being weakly totally anti-symmetric. Damm revealed 11 | * several methods to create totally anti-symmetric quasigroups of order 10 and 12 | * gave some examples in his doctoral dissertation. 13 | * 14 | * @see Wiki. Damm 15 | * algorithm 16 | */ 17 | public class Damm { 18 | 19 | /** 20 | * Weakly totally anti-symmetric quasigroup of order 10. This table is not 21 | * the only possible realisation of weak totally anti-symmetric quasigroup 22 | * but the most common one (taken from Damm doctoral dissertation). All 23 | * zeros lay on the diagonal because it simplifies the check digit 24 | * calculation. 25 | */ 26 | private static final byte[][] DAMM_TABLE = { 27 | {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, 28 | {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, 29 | {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, 30 | {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, 31 | {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, 32 | {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, 33 | {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, 34 | {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, 35 | {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, 36 | {2, 5, 8, 1, 4, 3, 6, 7, 9, 0} 37 | }; 38 | 39 | /** 40 | * Check input digits by Damm algorithm. 41 | * 42 | * @param digits input to check 43 | * @return true if check was successful, false otherwise 44 | * @throws IllegalArgumentException if input parameter contains not only 45 | * digits 46 | * @throws NullPointerException if input is null 47 | */ 48 | public static boolean dammCheck(String digits) { 49 | checkInput(digits); 50 | int[] numbers = toIntArray(digits); 51 | 52 | int checksum = 0; 53 | for (int number : numbers) { 54 | checksum = DAMM_TABLE[checksum][number]; 55 | } 56 | 57 | return checksum == 0; 58 | } 59 | 60 | /** 61 | * Calculate check digit for initial digits and add it tho the last 62 | * position. 63 | * 64 | * @param initialDigits initial value 65 | * @return digits with the checksum in the last position 66 | * @throws IllegalArgumentException if input parameter contains not only 67 | * digits 68 | * @throws NullPointerException if input is null 69 | */ 70 | public static String addDammChecksum(String initialDigits) { 71 | checkInput(initialDigits); 72 | int[] numbers = toIntArray(initialDigits); 73 | 74 | int checksum = 0; 75 | for (int number : numbers) { 76 | checksum = DAMM_TABLE[checksum][number]; 77 | } 78 | 79 | return initialDigits + checksum; 80 | } 81 | 82 | public static void main(String[] args) { 83 | System.out.println("Damm algorithm usage examples:"); 84 | var validInput = "5724"; 85 | var invalidInput = "5824"; 86 | checkAndPrint(validInput); 87 | checkAndPrint(invalidInput); 88 | 89 | System.out.println("\nCheck digit generation example:"); 90 | var input = "572"; 91 | generateAndPrint(input); 92 | } 93 | 94 | private static void checkAndPrint(String input) { 95 | String validationResult = Damm.dammCheck(input) 96 | ? "valid" 97 | : "not valid"; 98 | System.out.println("Input '" + input + "' is " + validationResult); 99 | } 100 | 101 | private static void generateAndPrint(String input) { 102 | String result = addDammChecksum(input); 103 | System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); 104 | } 105 | 106 | private static void checkInput(String input) { 107 | Objects.requireNonNull(input); 108 | if (!input.matches("\\d+")) { 109 | throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); 110 | } 111 | } 112 | 113 | private static int[] toIntArray(String string) { 114 | return string.chars() 115 | .map(i -> Character.digit(i, 10)) 116 | .toArray(); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Others/EulersFunction.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * You can read more about Euler's totient function 5 | * 6 | *

7 | * See https://en.wikipedia.org/wiki/Euler%27s_totient_function 8 | */ 9 | public class EulersFunction { 10 | // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time 11 | // complexity; 12 | 13 | public static int getEuler(int n) { 14 | int result = n; 15 | for (int i = 2; i * i <= n; i++) { 16 | if (n % i == 0) { 17 | while (n % i == 0) { 18 | n /= i; 19 | } 20 | result -= result / i; 21 | } 22 | } 23 | if (n > 1) { 24 | result -= result / n; 25 | } 26 | return result; 27 | } 28 | 29 | public static void main(String[] args) { 30 | for (int i = 1; i < 100; i++) { 31 | System.out.println(getEuler(i)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Others/FibbonaciSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Fibonacci sequence, and characterized by the fact that every number after the 7 | * first two is the sum of the two preceding ones. 8 | * 9 | *

10 | * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... 11 | * 12 | *

13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number 14 | * 15 | * Problem Statement: print all Fibonacci numbers that are smaller than your 16 | * given input N 17 | */ 18 | public class FibbonaciSeries { 19 | 20 | public static void main(String[] args) { 21 | // Get input from the user 22 | Scanner scan = new Scanner(System.in); 23 | int n = scan.nextInt(); 24 | int first = 0, second = 1; 25 | scan.close(); 26 | while (first <= n) { 27 | // print first fibo 0 then add second fibo into it while updating second as well 28 | System.out.println(first); 29 | int next = first + second; 30 | first = second; 31 | second = next; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class FloydTriangle { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 10 | int r = sc.nextInt(), n = 0; 11 | sc.close(); 12 | for (int i = 0; i < r; i++) { 13 | for (int j = 0; j <= i; j++) { 14 | System.out.print(++n + " "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Others/GuassLegendre.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Guass Legendre Algorithm ref 5 | * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm 6 | * 7 | * @author AKS1996 8 | */ 9 | public class GuassLegendre { 10 | 11 | public static void main(String[] args) { 12 | for (int i = 1; i <= 3; ++i) { 13 | System.out.println(pi(i)); 14 | } 15 | } 16 | 17 | static double pi(int l) { 18 | /* 19 | * l: No of loops to run 20 | */ 21 | 22 | double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; 23 | for (int i = 0; i < l; ++i) { 24 | double temp[] = update(a, b, t, p); 25 | a = temp[0]; 26 | b = temp[1]; 27 | t = temp[2]; 28 | p = temp[3]; 29 | } 30 | 31 | return Math.pow(a + b, 2) / (4 * t); 32 | } 33 | 34 | static double[] update(double a, double b, double t, double p) { 35 | double values[] = new double[4]; 36 | values[0] = (a + b) / 2; 37 | values[1] = Math.sqrt(a * b); 38 | values[2] = t - p * Math.pow(a - values[0], 2); 39 | values[3] = 2 * p; 40 | 41 | return values; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Others/HappyNumbersSeq.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | public class HappyNumbersSeq { 9 | private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | System.out.print("Enter number: "); 14 | int n = in.nextInt(); 15 | while (n != 1 && !isSad(n)) { 16 | System.out.print(n + " "); 17 | n = sumSquares(n); 18 | } 19 | String res = n == 1 ? "1 Happy number" : "Sad number"; 20 | System.out.println(res); 21 | } 22 | 23 | private static int sumSquares(int n) { 24 | int s = 0; 25 | for (; n > 0; n /= 10) { 26 | int r = n % 10; 27 | s += r * r; 28 | } 29 | return s; 30 | } 31 | 32 | private static boolean isSad(int n) { 33 | return CYCLE_NUMS.contains(n); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Others/Huffman.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.PriorityQueue; 4 | import java.util.Scanner; 5 | import java.util.Comparator; 6 | 7 | // node class is the basic structure 8 | // of each node present in the Huffman - tree. 9 | class HuffmanNode { 10 | 11 | int data; 12 | char c; 13 | 14 | HuffmanNode left; 15 | HuffmanNode right; 16 | } 17 | 18 | // comparator class helps to compare the node 19 | // on the basis of one of its attribute. 20 | // Here we will be compared 21 | // on the basis of data values of the nodes. 22 | class MyComparator implements Comparator { 23 | 24 | public int compare(HuffmanNode x, HuffmanNode y) { 25 | 26 | return x.data - y.data; 27 | } 28 | } 29 | 30 | public class Huffman { 31 | 32 | // recursive function to print the 33 | // huffman-code through the tree traversal. 34 | // Here s is the huffman - code generated. 35 | public static void printCode(HuffmanNode root, String s) { 36 | 37 | // base case; if the left and right are null 38 | // then its a leaf node and we print 39 | // the code s generated by traversing the tree. 40 | if (root.left 41 | == null 42 | && root.right 43 | == null 44 | && Character.isLetter(root.c)) { 45 | 46 | // c is the character in the node 47 | System.out.println(root.c + ":" + s); 48 | 49 | return; 50 | } 51 | 52 | // if we go to left then add "0" to the code. 53 | // if we go to the right add"1" to the code. 54 | // recursive calls for left and 55 | // right sub-tree of the generated tree. 56 | printCode(root.left, s + "0"); 57 | printCode(root.right, s + "1"); 58 | } 59 | 60 | // main function 61 | public static void main(String[] args) { 62 | 63 | Scanner s = new Scanner(System.in); 64 | 65 | // number of characters. 66 | int n = 6; 67 | char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; 68 | int[] charfreq = {5, 9, 12, 13, 16, 45}; 69 | 70 | // creating a priority queue q. 71 | // makes a min-priority queue(min-heap). 72 | PriorityQueue q 73 | = new PriorityQueue(n, new MyComparator()); 74 | 75 | for (int i = 0; i < n; i++) { 76 | 77 | // creating a Huffman node object 78 | // and add it to the priority queue. 79 | HuffmanNode hn = new HuffmanNode(); 80 | 81 | hn.c = charArray[i]; 82 | hn.data = charfreq[i]; 83 | 84 | hn.left = null; 85 | hn.right = null; 86 | 87 | // add functions adds 88 | // the huffman node to the queue. 89 | q.add(hn); 90 | } 91 | 92 | // create a root node 93 | HuffmanNode root = null; 94 | 95 | // Here we will extract the two minimum value 96 | // from the heap each time until 97 | // its size reduces to 1, extract until 98 | // all the nodes are extracted. 99 | while (q.size() > 1) { 100 | 101 | // first min extract. 102 | HuffmanNode x = q.peek(); 103 | q.poll(); 104 | 105 | // second min extarct. 106 | HuffmanNode y = q.peek(); 107 | q.poll(); 108 | 109 | // new node f which is equal 110 | HuffmanNode f = new HuffmanNode(); 111 | 112 | // to the sum of the frequency of the two nodes 113 | // assigning values to the f node. 114 | f.data = x.data + y.data; 115 | f.c = '-'; 116 | 117 | // first extracted node as left child. 118 | f.left = x; 119 | 120 | // second extracted node as the right child. 121 | f.right = y; 122 | 123 | // marking the f node as the root node. 124 | root = f; 125 | 126 | // add this node to the priority-queue. 127 | q.add(f); 128 | } 129 | 130 | // print the codes by traversing the tree 131 | printCode(root, ""); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /Others/InsertDeleteInArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | public class InsertDeleteInArray { 6 | 7 | public static void main(String[] args) { 8 | Scanner s = new Scanner(System.in); // Input statement 9 | System.out.println("Enter the size of the array"); 10 | int size = s.nextInt(); 11 | int a[] = new int[size]; 12 | int i; 13 | 14 | // To enter the initial elements 15 | for (i = 0; i < size; i++) { 16 | System.out.println("Enter the element"); 17 | a[i] = s.nextInt(); 18 | } 19 | 20 | // To insert a new element(we are creating a new array) 21 | System.out.println("Enter the index at which the element should be inserted"); 22 | int insert_pos = s.nextInt(); 23 | System.out.println("Enter the element to be inserted"); 24 | int ins = s.nextInt(); 25 | int size2 = size + 1; 26 | int b[] = new int[size2]; 27 | for (i = 0; i < size2; i++) { 28 | if (i <= insert_pos) { 29 | b[i] = a[i]; 30 | } else { 31 | b[i] = a[i - 1]; 32 | } 33 | } 34 | b[insert_pos] = ins; 35 | for (i = 0; i < size2; i++) { 36 | System.out.println(b[i]); 37 | } 38 | 39 | // To delete an element given the index 40 | System.out.println("Enter the index at which element is to be deleted"); 41 | int del_pos = s.nextInt(); 42 | for (i = del_pos; i < size2 - 1; i++) { 43 | b[i] = b[i + 1]; 44 | } 45 | for (i = 0; i < size2 - 1; i++) { 46 | System.out.println(b[i]); 47 | } 48 | s.close(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Others/KMP.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function 5 | * for an example 6 | */ 7 | public class KMP { 8 | // a working example 9 | 10 | public static void main(String[] args) { 11 | final String haystack = "AAAAABAAABA"; // This is the full string 12 | final String needle = "AAAA"; // This is the substring that we want to find 13 | KMPmatcher(haystack, needle); 14 | } 15 | 16 | // find the starting index in string haystack[] that matches the search word P[] 17 | public static void KMPmatcher(final String haystack, final String needle) { 18 | final int m = haystack.length(); 19 | final int n = needle.length(); 20 | final int[] pi = computePrefixFunction(needle); 21 | int q = 0; 22 | for (int i = 0; i < m; i++) { 23 | while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { 24 | q = pi[q - 1]; 25 | } 26 | 27 | if (haystack.charAt(i) == needle.charAt(q)) { 28 | q++; 29 | } 30 | 31 | if (q == n) { 32 | System.out.println("Pattern starts: " + (i + 1 - n)); 33 | q = pi[q - 1]; 34 | } 35 | } 36 | } 37 | 38 | // return the prefix function 39 | private static int[] computePrefixFunction(final String P) { 40 | final int n = P.length(); 41 | final int[] pi = new int[n]; 42 | pi[0] = 0; 43 | int q = 0; 44 | for (int i = 1; i < n; i++) { 45 | while (q > 0 && P.charAt(q) != P.charAt(i)) { 46 | q = pi[q - 1]; 47 | } 48 | 49 | if (P.charAt(q) == P.charAt(i)) { 50 | q++; 51 | } 52 | 53 | pi[i] = q; 54 | } 55 | return pi; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class Krishnamurthy { 6 | 7 | static int fact(int n) { 8 | int i, p = 1; 9 | for (i = n; i >= 1; i--) { 10 | p = p * i; 11 | } 12 | return p; 13 | } 14 | 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int a, b, s = 0; 18 | System.out.print("Enter the number : "); 19 | a = sc.nextInt(); 20 | int n = a; 21 | while (a > 0) { 22 | b = a % 10; 23 | s = s + fact(b); 24 | a = a / 10; 25 | } 26 | if (s == n) { 27 | System.out.print(n + " is a krishnamurthy number"); 28 | } else { 29 | System.out.print(n + " is not a krishnamurthy number"); 30 | } 31 | sc.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Others/LinearCongruentialGenerator.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * * 5 | * A pseudorandom number generator. 6 | * 7 | * @author Tobias Carryer 8 | * @date October 10, 2017 9 | */ 10 | public class LinearCongruentialGenerator { 11 | 12 | private double a, c, m, previousValue; 13 | 14 | /** 15 | * * 16 | * These parameters are saved and used when nextNumber() is called. The 17 | * current timestamp in milliseconds is used as the seed. 18 | * 19 | * @param multiplier 20 | * @param increment 21 | * @param modulo The maximum number that can be generated (exclusive). A 22 | * common value is 2^32. 23 | */ 24 | public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { 25 | this(System.currentTimeMillis(), multiplier, increment, modulo); 26 | } 27 | 28 | /** 29 | * * 30 | * These parameters are saved and used when nextNumber() is called. 31 | * 32 | * @param seed 33 | * @param multiplier 34 | * @param increment 35 | * @param modulo The maximum number that can be generated (exclusive). A 36 | * common value is 2^32. 37 | */ 38 | public LinearCongruentialGenerator( 39 | double seed, double multiplier, double increment, double modulo) { 40 | this.previousValue = seed; 41 | this.a = multiplier; 42 | this.c = increment; 43 | this.m = modulo; 44 | } 45 | 46 | /** 47 | * The smallest number that can be generated is zero. The largest number 48 | * that can be generated is modulo-1. modulo is set in the constructor. 49 | * 50 | * @return a pseudorandom number. 51 | */ 52 | public double nextNumber() { 53 | previousValue = (a * previousValue + c) % m; 54 | return previousValue; 55 | } 56 | 57 | public static void main(String[] args) { 58 | // Show the LCG in action. 59 | // Decisive proof that the LCG works could be made by adding each number 60 | // generated to a Set while checking for duplicates. 61 | LinearCongruentialGenerator lcg 62 | = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0)); 63 | for (int i = 0; i < 512; i++) { 64 | System.out.println(lcg.nextNumber()); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Others/MiniMaxAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | /** 7 | * MiniMax is an algorithm used int artificial intelligence and game theory for 8 | * minimizing the possible loss for the worst case scenario. 9 | * 10 | * See more (https://en.wikipedia.org/wiki/Minimax, 11 | * https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/). 12 | * 13 | * @author aitofi (https://github.com/aitorfi) 14 | */ 15 | public class MiniMaxAlgorithm { 16 | 17 | /** 18 | * Game tree represented as an int array containing scores. Each array 19 | * element is a leaf node. 20 | */ 21 | private int[] scores; 22 | private int height; 23 | 24 | /** 25 | * Initializes the scores with 8 random leaf nodes 26 | */ 27 | public MiniMaxAlgorithm() { 28 | scores = getRandomScores(3, 99); 29 | height = log2(scores.length); 30 | } 31 | 32 | public static void main(String[] args) { 33 | MiniMaxAlgorithm miniMaxAlgorith = new MiniMaxAlgorithm(); 34 | boolean isMaximizer = true; // Specifies the player that goes first. 35 | boolean verbose = true; // True to show each players choices. 36 | int bestScore; 37 | 38 | bestScore = miniMaxAlgorith.miniMax(0, isMaximizer, 0, verbose); 39 | 40 | if (verbose) { 41 | System.out.println(); 42 | } 43 | 44 | System.out.println(Arrays.toString(miniMaxAlgorith.getScores())); 45 | System.out.println( 46 | "The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + String.valueOf(bestScore)); 47 | } 48 | 49 | /** 50 | * Returns the optimal score assuming that both players play their best. 51 | * 52 | * @param depth Indicates how deep we are into the game tree. 53 | * @param isMaximizer True if it is maximizers turn; otherwise false. 54 | * @param index Index of the leaf node that is being evaluated. 55 | * @param verbose True to show each players choices. 56 | * @return The optimal score for the player that made the first move. 57 | */ 58 | public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { 59 | int bestScore, score1, score2; 60 | 61 | if (depth == height) { // Leaf node reached. 62 | return scores[index]; 63 | } 64 | 65 | score1 = miniMax(depth + 1, !isMaximizer, index * 2, verbose); 66 | score2 = miniMax(depth + 1, !isMaximizer, (index * 2) + 1, verbose); 67 | 68 | if (isMaximizer) { 69 | // Maximizer player wants to get the maximum possible score. 70 | bestScore = Math.max(score1, score2); 71 | } else { 72 | // Minimizer player wants to get the minimum possible score. 73 | bestScore = Math.min(score1, score2); 74 | } 75 | 76 | // Leaf nodes can be sequentially inspected by 77 | // recurssively multiplying (0 * 2) and ((0 * 2) + 1): 78 | // (0 x 2) = 0; ((0 x 2) + 1) = 1 79 | // (1 x 2) = 2; ((1 x 2) + 1) = 3 80 | // (2 x 2) = 4; ((2 x 2) + 1) = 5 ... 81 | if (verbose) { 82 | System.out.println(String.format("From %02d and %02d, %s chooses %02d", score1, score2, 83 | (isMaximizer ? "Maximizer" : "Minimizer"), bestScore)); 84 | } 85 | 86 | return bestScore; 87 | } 88 | 89 | /** 90 | * Returns an array of random numbers which lenght is a power of 2. 91 | * 92 | * @param size The power of 2 that will determine the lenght of the array. 93 | * @param maxScore The maximum possible score. 94 | * @return An array of random numbers. 95 | */ 96 | public static int[] getRandomScores(int size, int maxScore) { 97 | int[] randomScores = new int[(int) Math.pow(2, size)]; 98 | Random rand = new Random(); 99 | 100 | for (int i = 0; i < randomScores.length; i++) { 101 | randomScores[i] = rand.nextInt(maxScore) + 1; 102 | } 103 | 104 | return randomScores; 105 | } 106 | 107 | // A utility function to find Log n in base 2 108 | private int log2(int n) { 109 | return (n == 1) ? 0 : log2(n / 2) + 1; 110 | } 111 | 112 | public void setScores(int[] scores) { 113 | if (scores.length % 1 == 0) { 114 | this.scores = scores; 115 | height = log2(this.scores.length); 116 | } else { 117 | System.out.println("The number of scores must be a power of 2."); 118 | } 119 | } 120 | 121 | public int[] getScores() { 122 | return scores; 123 | } 124 | 125 | public int getHeight() { 126 | return height; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Others/PageRank.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | class PageRank { 6 | 7 | public static void main(String args[]) { 8 | int nodes, i, j; 9 | Scanner in = new Scanner(System.in); 10 | System.out.print("Enter the Number of WebPages: "); 11 | nodes = in.nextInt(); 12 | PageRank p = new PageRank(); 13 | System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); 14 | for (i = 1; i <= nodes; i++) { 15 | for (j = 1; j <= nodes; j++) { 16 | p.path[i][j] = in.nextInt(); 17 | if (j == i) { 18 | p.path[i][j] = 0; 19 | } 20 | } 21 | } 22 | p.calc(nodes); 23 | } 24 | 25 | public int path[][] = new int[10][10]; 26 | public double pagerank[] = new double[10]; 27 | 28 | public void calc(double totalNodes) { 29 | 30 | double InitialPageRank; 31 | double OutgoingLinks = 0; 32 | double DampingFactor = 0.85; 33 | double TempPageRank[] = new double[10]; 34 | int ExternalNodeNumber; 35 | int InternalNodeNumber; 36 | int k = 1; // For Traversing 37 | int ITERATION_STEP = 1; 38 | InitialPageRank = 1 / totalNodes; 39 | System.out.printf( 40 | " Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); 41 | 42 | // 0th ITERATION _ OR _ INITIALIZATION PHASE // 43 | for (k = 1; k <= totalNodes; k++) { 44 | this.pagerank[k] = InitialPageRank; 45 | } 46 | System.out.printf("\n Initial PageRank Values , 0th Step \n"); 47 | 48 | for (k = 1; k <= totalNodes; k++) { 49 | System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); 50 | } 51 | 52 | while (ITERATION_STEP <= 2) // Iterations 53 | { 54 | // Store the PageRank for All Nodes in Temporary Array 55 | for (k = 1; k <= totalNodes; k++) { 56 | TempPageRank[k] = this.pagerank[k]; 57 | this.pagerank[k] = 0; 58 | } 59 | 60 | for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { 61 | for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) { 62 | if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) { 63 | k = 1; 64 | OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber 65 | while (k <= totalNodes) { 66 | if (this.path[ExternalNodeNumber][k] == 1) { 67 | OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links 68 | } 69 | k = k + 1; 70 | } 71 | // Calculate PageRank 72 | this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); 73 | } 74 | } 75 | System.out.printf("\n After " + ITERATION_STEP + "th Step \n"); 76 | 77 | for (k = 1; k <= totalNodes; k++) { 78 | System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); 79 | } 80 | 81 | ITERATION_STEP = ITERATION_STEP + 1; 82 | } 83 | 84 | // Add the Damping Factor to PageRank 85 | for (k = 1; k <= totalNodes; k++) { 86 | this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k]; 87 | } 88 | 89 | // Display PageRank 90 | System.out.printf("\n Final Page Rank : \n"); 91 | for (k = 1; k <= totalNodes; k++) { 92 | System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); 93 | } 94 | 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Others/PasswordGen.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | /** 9 | * Creates a random password from ASCII letters Given password length bounds 10 | * 11 | * @author AKS1996 12 | * @date 2017.10.25 13 | */ 14 | class PasswordGen { 15 | 16 | public static void main(String args[]) { 17 | String password = generatePassword(8, 16); 18 | System.out.print("Password: " + password); 19 | } 20 | 21 | static String generatePassword(int min_length, int max_length) { 22 | Random random = new Random(); 23 | 24 | String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 25 | String lower = "abcdefghijklmnopqrstuvwxyz"; 26 | String numbers = "0123456789"; 27 | String specialChars = "!@#$%^&*(){}?"; 28 | 29 | String allChars = upper + lower + numbers + specialChars; 30 | 31 | List letters = new ArrayList(); 32 | for (char c : allChars.toCharArray()) { 33 | letters.add(c); 34 | } 35 | 36 | // Inbuilt method to randomly shuffle a elements of a list 37 | Collections.shuffle(letters); 38 | StringBuilder password = new StringBuilder(); 39 | 40 | // Note that size of the password is also random 41 | for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { 42 | password.append(letters.get(random.nextInt(letters.size()))); 43 | } 44 | 45 | return password.toString(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Others/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Others/RabinKarp.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) 5 | */ 6 | import java.util.Scanner; 7 | 8 | // An implementation of Rabin-Karp string matching algorithm 9 | // Program will simply end if there is no match 10 | public class RabinKarp { 11 | 12 | public static Scanner scanner = null; 13 | public static final int d = 256; 14 | 15 | public static void main(String[] args) { 16 | 17 | scanner = new Scanner(System.in); 18 | System.out.println("Enter String"); 19 | String text = scanner.nextLine(); 20 | System.out.println("Enter pattern"); 21 | String pattern = scanner.nextLine(); 22 | 23 | int q = 101; 24 | searchPat(text, pattern, q); 25 | } 26 | 27 | private static void searchPat(String text, String pattern, int q) { 28 | 29 | int m = pattern.length(); 30 | int n = text.length(); 31 | int t = 0; 32 | int p = 0; 33 | int h = 1; 34 | int j = 0; 35 | int i = 0; 36 | 37 | h = (int) Math.pow(d, m - 1) % q; 38 | 39 | for (i = 0; i < m; i++) { 40 | // hash value is calculated for each character and then added with the hash value of the next 41 | // character for pattern 42 | // as well as the text for length equal to the length of pattern 43 | p = (d * p + pattern.charAt(i)) % q; 44 | t = (d * t + text.charAt(i)) % q; 45 | } 46 | 47 | for (i = 0; i <= n - m; i++) { 48 | 49 | // if the calculated hash value of the pattern and text matches then 50 | // all the characters of the pattern is matched with the text of length equal to length of the 51 | // pattern 52 | // if all matches then pattern exist in string 53 | // if not then the hash value of the first character of the text is subtracted and hash value 54 | // of the next character after the end 55 | // of the evaluated characters is added 56 | if (p == t) { 57 | 58 | // if hash value matches then the individual characters are matched 59 | for (j = 0; j < m; j++) { 60 | 61 | // if not matched then break out of the loop 62 | if (text.charAt(i + j) != pattern.charAt(j)) { 63 | break; 64 | } 65 | } 66 | 67 | // if all characters are matched then pattern exist in the string 68 | if (j == m) { 69 | System.out.println("Pattern found at index " + i); 70 | } 71 | } 72 | 73 | // if i stack = new Stack<>(); 10 | 11 | // Main function 12 | public static void main(String[] args) { 13 | // To Create a Dummy Stack containing integers from 0-9 14 | for (int i = 0; i < 10; i++) { 15 | stack.push(i); 16 | } 17 | System.out.println("STACK"); 18 | 19 | // To print that dummy Stack 20 | for (int k = 9; k >= 0; k--) { 21 | System.out.println(k); 22 | } 23 | 24 | // Reverse Function called 25 | reverseUsingRecursion(stack); 26 | 27 | System.out.println("REVERSED STACK : "); 28 | // To print reversed stack 29 | while (!stack.isEmpty()) { 30 | System.out.println(stack.pop()); 31 | } 32 | } 33 | 34 | // Function Used to reverse Stack Using Recursion 35 | private static void reverseUsingRecursion(Stack stack) { 36 | if (stack.isEmpty()) // If stack is empty then return 37 | { 38 | return; 39 | } 40 | /* All items are stored in call stack until we reach the end*/ 41 | 42 | int temptop = stack.peek(); 43 | stack.pop(); 44 | reverseUsingRecursion(stack); // Recursion call 45 | insertAtEnd(temptop); // Insert items held in call stack one by one into stack 46 | } 47 | 48 | // Function used to insert element at the end of stack 49 | private static void insertAtEnd(int temptop) { 50 | if (stack.isEmpty()) { 51 | stack.push(temptop); // If stack is empty push the element 52 | } else { 53 | int temp = stack.peek(); 54 | /* All the items are stored in call stack until we reach end*/ 55 | stack.pop(); 56 | 57 | insertAtEnd(temptop); // Recursive call 58 | 59 | stack.push(temp); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Others/RootPrecision.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RootPrecision { 6 | 7 | public static void main(String[] args) { 8 | // take input 9 | Scanner scn = new Scanner(System.in); 10 | 11 | // N is the input number 12 | int N = scn.nextInt(); 13 | 14 | // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. 15 | int P = scn.nextInt(); 16 | System.out.println(squareRoot(N, P)); 17 | 18 | scn.close(); 19 | } 20 | 21 | public static double squareRoot(int N, int P) { 22 | // rv means return value 23 | double rv; 24 | 25 | double root = Math.pow(N, 0.5); 26 | 27 | // calculate precision to power of 10 and then multiply it with root value. 28 | int precision = (int) Math.pow(10, P); 29 | root = root * precision; 30 | /*typecast it into integer then divide by precision and again typecast into double 31 | so as to have decimal points upto P precision */ 32 | 33 | rv = (int) root; 34 | return rv / precision; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Others/RotateMatriceBy90Degree.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here 5 | * is the algorithm for this problem . 6 | */ 7 | import java.util.*; 8 | 9 | class Rotate_by_90_degree { 10 | 11 | public static void main(String[] args) { 12 | Scanner sc = new Scanner(System.in); 13 | int t = sc.nextInt(); 14 | 15 | while (t-- > 0) { 16 | int n = sc.nextInt(); 17 | int[][] arr = new int[n][n]; 18 | 19 | for (int i = 0; i < n; i++) { 20 | for (int j = 0; j < n; j++) { 21 | arr[i][j] = sc.nextInt(); 22 | } 23 | } 24 | 25 | Rotate g = new Rotate(); 26 | g.rotate(arr); 27 | printMatrix(arr); 28 | } 29 | sc.close(); 30 | } 31 | 32 | static void printMatrix(int arr[][]) { 33 | for (int i = 0; i < arr.length; i++) { 34 | for (int j = 0; j < arr[0].length; j++) { 35 | System.out.print(arr[i][j] + " "); 36 | } 37 | System.out.println(""); 38 | } 39 | } 40 | } 41 | 42 | /** 43 | * Class containing the algo to roate matrix by 90 degree 44 | */ 45 | class Rotate { 46 | 47 | static void rotate(int a[][]) { 48 | int n = a.length; 49 | for (int i = 0; i < n; i++) { 50 | for (int j = 0; j < n; j++) { 51 | if (i > j) { 52 | int temp = a[i][j]; 53 | a[i][j] = a[j][i]; 54 | a[j][i] = temp; 55 | } 56 | } 57 | } 58 | int i = 0, k = n - 1; 59 | while (i < k) { 60 | for (int j = 0; j < n; j++) { 61 | int temp = a[i][j]; 62 | a[i][j] = a[k][j]; 63 | a[k][j] = temp; 64 | } 65 | 66 | i++; 67 | k--; 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Others/SieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers 7 | * up to any given limit. It does so by iteratively marking as composite (i.e., 8 | * not prime) the multiples of each prime, starting with the first prime number, 9 | * 2. The multiples of a given prime are generated as a sequence of numbers 10 | * starting from that prime, with constant difference between them that is equal 11 | * to that prime. This is the sieve's key distinction from using trial division 12 | * to sequentially test each candidate number for divisibility by each prime. 13 | * Once all the multiples of each discovered prime have been marked as 14 | * composites, the remaining unmarked numbers are primes. 15 | *

16 | * Poetry about Sieve of Eratosthenes: 17 | *

18 | * Sift the Two's and Sift the Three's:

19 | *

20 | * The Sieve of Eratosthenes.

21 | *

22 | * When the multiples sublime,

23 | *

24 | * The numbers that remain are Prime.

25 | * 26 | * @see Wiki 27 | */ 28 | public class SieveOfEratosthenes { 29 | 30 | /** 31 | * @param n The number till which we have to check for prime Prints all the 32 | * prime numbers till n. Should be more than 1. 33 | * @return array of all prime numbers between 0 to n 34 | */ 35 | public static int[] findPrimesTill(int n) { 36 | // Create array where index is number and value is flag - is that number a prime or not. 37 | // size of array is n + 1 cause in Java array indexes starts with 0 38 | Type[] numbers = new Type[n + 1]; 39 | 40 | // Start with assumption that all numbers except 0 and 1 are primes. 41 | Arrays.fill(numbers, Type.PRIME); 42 | numbers[0] = numbers[1] = Type.NOT_PRIME; 43 | 44 | double cap = Math.sqrt(n); 45 | // Main algorithm: mark all numbers which are multiples of some other values as not prime 46 | for (int i = 2; i <= cap; i++) { 47 | if (numbers[i] == Type.PRIME) { 48 | for (int j = 2; i * j <= n; j++) { 49 | numbers[i * j] = Type.NOT_PRIME; 50 | } 51 | } 52 | } 53 | 54 | //Write all primes to result array 55 | int primesCount = (int) Arrays.stream(numbers) 56 | .filter(element -> element == Type.PRIME) 57 | .count(); 58 | int[] primes = new int[primesCount]; 59 | 60 | int primeIndex = 0; 61 | for (int i = 0; i < n + 1; i++) { 62 | if (numbers[i] == Type.PRIME) { 63 | primes[primeIndex++] = i; 64 | } 65 | } 66 | 67 | return primes; 68 | } 69 | 70 | private enum Type { 71 | PRIME, NOT_PRIME 72 | } 73 | 74 | public static void main(String[] args) { 75 | int n = 100; 76 | System.out.println("Searching for all primes from zero to " + n); 77 | int[] primes = findPrimesTill(n); 78 | System.out.println("Found: " + Arrays.toString(primes)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Others/SkylineProblem.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.Scanner; 6 | 7 | public class SkylineProblem { 8 | 9 | Building[] building; 10 | int count; 11 | 12 | public void run() { 13 | Scanner sc = new Scanner(System.in); 14 | 15 | int num = sc.nextInt(); 16 | this.building = new Building[num]; 17 | 18 | for (int i = 0; i < num; i++) { 19 | String input = sc.next(); 20 | String[] data = input.split(","); 21 | this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); 22 | } 23 | this.print(this.findSkyline(0, num - 1)); 24 | 25 | sc.close(); 26 | } 27 | 28 | public void add(int left, int height, int right) { 29 | building[count++] = new Building(left, height, right); 30 | } 31 | 32 | public void print(ArrayList skyline) { 33 | Iterator it = skyline.iterator(); 34 | 35 | while (it.hasNext()) { 36 | Skyline temp = it.next(); 37 | System.out.print(temp.coordinates + "," + temp.height); 38 | if (it.hasNext()) { 39 | System.out.print(","); 40 | } 41 | } 42 | } 43 | 44 | public ArrayList findSkyline(int start, int end) { 45 | if (start == end) { 46 | ArrayList list = new ArrayList<>(); 47 | list.add(new Skyline(building[start].left, building[start].height)); 48 | list.add(new Skyline(building[end].right, 0)); 49 | 50 | return list; 51 | } 52 | 53 | int mid = (start + end) / 2; 54 | 55 | ArrayList sky1 = this.findSkyline(start, mid); 56 | ArrayList sky2 = this.findSkyline(mid + 1, end); 57 | 58 | return this.mergeSkyline(sky1, sky2); 59 | } 60 | 61 | public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { 62 | int currentH1 = 0, currentH2 = 0; 63 | ArrayList skyline = new ArrayList<>(); 64 | int maxH = 0; 65 | 66 | while (!sky1.isEmpty() && !sky2.isEmpty()) { 67 | if (sky1.get(0).coordinates < sky2.get(0).coordinates) { 68 | int currentX = sky1.get(0).coordinates; 69 | currentH1 = sky1.get(0).height; 70 | 71 | if (currentH1 < currentH2) { 72 | sky1.remove(0); 73 | if (maxH != currentH2) { 74 | skyline.add(new Skyline(currentX, currentH2)); 75 | } 76 | } else { 77 | maxH = currentH1; 78 | sky1.remove(0); 79 | skyline.add(new Skyline(currentX, currentH1)); 80 | } 81 | } else { 82 | int currentX = sky2.get(0).coordinates; 83 | currentH2 = sky2.get(0).height; 84 | 85 | if (currentH2 < currentH1) { 86 | sky2.remove(0); 87 | if (maxH != currentH1) { 88 | skyline.add(new Skyline(currentX, currentH1)); 89 | } 90 | } else { 91 | maxH = currentH2; 92 | sky2.remove(0); 93 | skyline.add(new Skyline(currentX, currentH2)); 94 | } 95 | } 96 | } 97 | 98 | while (!sky1.isEmpty()) { 99 | skyline.add(sky1.get(0)); 100 | sky1.remove(0); 101 | } 102 | 103 | while (!sky2.isEmpty()) { 104 | skyline.add(sky2.get(0)); 105 | sky2.remove(0); 106 | } 107 | 108 | return skyline; 109 | } 110 | 111 | public class Skyline { 112 | 113 | public int coordinates; 114 | public int height; 115 | 116 | public Skyline(int coordinates, int height) { 117 | this.coordinates = coordinates; 118 | this.height = height; 119 | } 120 | } 121 | 122 | public class Building { 123 | 124 | public int left; 125 | public int height; 126 | public int right; 127 | 128 | public Building(int left, int height, int right) { 129 | this.left = left; 130 | this.height = height; 131 | this.right = right; 132 | } 133 | } 134 | 135 | public static void main(String[] args) { 136 | SkylineProblem skylineProblem = new SkylineProblem(); 137 | skylineProblem.run(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /Others/StackPostfixNotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | public class StackPostfixNotation { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" 10 | System.out.println(postfixEvaluate(post)); 11 | scanner.close(); 12 | } 13 | 14 | // Evaluates the given postfix expression string and returns the result. 15 | public static int postfixEvaluate(String exp) { 16 | Stack s = new Stack(); 17 | Scanner tokens = new Scanner(exp); 18 | 19 | while (tokens.hasNext()) { 20 | if (tokens.hasNextInt()) { 21 | s.push(tokens.nextInt()); // If int then push to stack 22 | } else { // else pop top two values and perform the operation 23 | int num2 = s.pop(); 24 | int num1 = s.pop(); 25 | String op = tokens.next(); 26 | 27 | if (op.equals("+")) { 28 | s.push(num1 + num2); 29 | } else if (op.equals("-")) { 30 | s.push(num1 - num2); 31 | } else if (op.equals("*")) { 32 | s.push(num1 * num2); 33 | } else { 34 | s.push(num1 / num2); 35 | } 36 | 37 | // "+", "-", "*", "/" 38 | } 39 | } 40 | tokens.close(); 41 | return s.pop(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Others/StringMatchFiniteAutomata.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon) 5 | */ 6 | import java.util.Scanner; 7 | 8 | // An implementaion of string matching using finite automata 9 | public class StringMatchFiniteAutomata { 10 | 11 | public static final int CHARS = 256; 12 | public static int[][] FA; 13 | public static Scanner scanner = null; 14 | 15 | public static void main(String[] args) { 16 | 17 | scanner = new Scanner(System.in); 18 | System.out.println("Enter String"); 19 | String text = scanner.nextLine(); 20 | System.out.println("Enter pattern"); 21 | String pat = scanner.nextLine(); 22 | 23 | searchPat(text, pat); 24 | 25 | scanner.close(); 26 | } 27 | 28 | public static void searchPat(String text, String pat) { 29 | 30 | int m = pat.length(); 31 | int n = text.length(); 32 | 33 | FA = new int[m + 1][CHARS]; 34 | 35 | computeFA(pat, m, FA); 36 | 37 | int state = 0; 38 | for (int i = 0; i < n; i++) { 39 | state = FA[state][text.charAt(i)]; 40 | 41 | if (state == m) { 42 | System.out.println("Pattern found at index " + (i - m + 1)); 43 | } 44 | } 45 | } 46 | 47 | // Computes finite automata for the partern 48 | public static void computeFA(String pat, int m, int[][] FA) { 49 | 50 | for (int state = 0; state <= m; ++state) { 51 | for (int x = 0; x < CHARS; ++x) { 52 | FA[state][x] = getNextState(pat, m, state, x); 53 | } 54 | } 55 | } 56 | 57 | public static int getNextState(String pat, int m, int state, int x) { 58 | 59 | // if current state is less than length of pattern 60 | // and input character of pattern matches the character in the alphabet 61 | // then automata goes to next state 62 | if (state < m && x == pat.charAt(state)) { 63 | return state + 1; 64 | } 65 | 66 | for (int ns = state; ns > 0; ns--) { 67 | 68 | if (pat.charAt(ns - 1) == x) { 69 | 70 | for (int i = 0; i < ns - 1; i++) { 71 | 72 | if (pat.charAt(i) != pat.charAt(state - ns + i + 1)) { 73 | break; 74 | } 75 | 76 | if (i == ns - 1) { 77 | return ns; 78 | } 79 | } 80 | } 81 | } 82 | 83 | return 0; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Others/Sudoku.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | class Sudoku { 4 | 5 | public static boolean isSafe(int[][] board, 6 | int row, int col, 7 | int num) { 8 | // Row has the unique (row-clash) 9 | for (int d = 0; d < board.length; d++) { 10 | 11 | // Check if the number we are trying to 12 | // place is already present in 13 | // that row, return false; 14 | if (board[row][d] == num) { 15 | return false; 16 | } 17 | } 18 | 19 | // Column has the unique numbers (column-clash) 20 | for (int r = 0; r < board.length; r++) { 21 | 22 | // Check if the number 23 | // we are trying to 24 | // place is already present in 25 | // that column, return false; 26 | if (board[r][col] == num) { 27 | return false; 28 | } 29 | } 30 | 31 | // Corresponding square has 32 | // unique number (box-clash) 33 | int sqrt = (int) Math.sqrt(board.length); 34 | int boxRowStart = row - row % sqrt; 35 | int boxColStart = col - col % sqrt; 36 | 37 | for (int r = boxRowStart; 38 | r < boxRowStart + sqrt; r++) { 39 | for (int d = boxColStart; 40 | d < boxColStart + sqrt; d++) { 41 | if (board[r][d] == num) { 42 | return false; 43 | } 44 | } 45 | } 46 | 47 | // if there is no clash, it's safe 48 | return true; 49 | } 50 | 51 | public static boolean solveSudoku( 52 | int[][] board, int n) { 53 | int row = -1; 54 | int col = -1; 55 | boolean isEmpty = true; 56 | for (int i = 0; i < n; i++) { 57 | for (int j = 0; j < n; j++) { 58 | if (board[i][j] == 0) { 59 | row = i; 60 | col = j; 61 | 62 | // We still have some remaining 63 | // missing values in Sudoku 64 | isEmpty = false; 65 | break; 66 | } 67 | } 68 | if (!isEmpty) { 69 | break; 70 | } 71 | } 72 | 73 | // No empty space left 74 | if (isEmpty) { 75 | return true; 76 | } 77 | 78 | // Else for each-row backtrack 79 | for (int num = 1; num <= n; num++) { 80 | if (isSafe(board, row, col, num)) { 81 | board[row][col] = num; 82 | if (solveSudoku(board, n)) { 83 | // print(board, n); 84 | return true; 85 | } else { 86 | // replace it 87 | board[row][col] = 0; 88 | } 89 | } 90 | } 91 | return false; 92 | } 93 | 94 | public static void print( 95 | int[][] board, int N) { 96 | 97 | // We got the answer, just print it 98 | for (int r = 0; r < N; r++) { 99 | for (int d = 0; d < N; d++) { 100 | System.out.print(board[r][d]); 101 | System.out.print(" "); 102 | } 103 | System.out.print("\n"); 104 | 105 | if ((r + 1) % (int) Math.sqrt(N) == 0) { 106 | System.out.print(""); 107 | } 108 | } 109 | } 110 | 111 | // Driver Code 112 | public static void main(String args[]) { 113 | 114 | int[][] board = new int[][]{ 115 | {3, 0, 6, 5, 0, 8, 4, 0, 0}, 116 | {5, 2, 0, 0, 0, 0, 0, 0, 0}, 117 | {0, 8, 7, 0, 0, 0, 0, 3, 1}, 118 | {0, 0, 3, 0, 1, 0, 0, 8, 0}, 119 | {9, 0, 0, 8, 6, 3, 0, 0, 5}, 120 | {0, 5, 0, 0, 9, 0, 6, 0, 0}, 121 | {1, 3, 0, 0, 0, 0, 2, 5, 0}, 122 | {0, 0, 0, 0, 0, 0, 0, 7, 4}, 123 | {0, 0, 5, 2, 0, 6, 3, 0, 0} 124 | }; 125 | int N = board.length; 126 | 127 | if (solveSudoku(board, N)) { 128 | // print solution 129 | print(board, N); 130 | } else { 131 | System.out.println("No solution"); 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /Others/ThreeSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * To find triplet equals to given sum in complexity O(n*log(n)) 8 | * 9 | *

10 | * Array must be sorted 11 | * 12 | * @author Ujjawal Joshi 13 | * @date 2020.05.18 14 | *

15 | * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 16 | * Explanation: There is a triplet (12, 3 and 9) present in the array whose sum 17 | * is 24. 18 | */ 19 | class ThreeSum { 20 | 21 | public static void main(String args[]) { 22 | Scanner sc = new Scanner(System.in); 23 | int n = sc.nextInt(); // Length of an array 24 | 25 | int a[] = new int[n]; 26 | 27 | for (int i = 0; i < n; i++) { 28 | a[i] = sc.nextInt(); 29 | } 30 | System.out.println("Target"); 31 | int n_find = sc.nextInt(); 32 | 33 | Arrays.sort(a); // Sort the array if array is not sorted 34 | 35 | for (int i = 0; i < n; i++) { 36 | 37 | int l = i + 1, r = n - 1; 38 | 39 | while (l < r) { 40 | if (a[i] + a[l] + a[r] == n_find) { 41 | System.out.println(a[i] + " " + a[l] + " " + a[r]); 42 | break; 43 | } // if you want all the triplets write l++;r--; insted of break; 44 | else if (a[i] + a[l] + a[r] < n_find) { 45 | l++; 46 | } else { 47 | r--; 48 | } 49 | } 50 | } 51 | 52 | sc.close(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Others/TopKWords.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | /* display the most frequent K words in the file and the times it appear 7 | in the file – shown in order (ignore case and periods) */ 8 | public class TopKWords { 9 | 10 | static class CountWords { 11 | 12 | private String fileName; 13 | 14 | public CountWords(String fileName) { 15 | this.fileName = fileName; 16 | } 17 | 18 | public Map getDictionary() { 19 | Map dictionary = new HashMap<>(); 20 | FileInputStream fis = null; 21 | 22 | try { 23 | 24 | fis = new FileInputStream(fileName); // open the file 25 | int in = 0; 26 | String s = ""; // init a empty word 27 | in = fis.read(); // read one character 28 | 29 | while (-1 != in) { 30 | if (Character.isLetter((char) in)) { 31 | s += (char) in; // if get a letter, append to s 32 | } else { 33 | // this branch means an entire word has just been read 34 | if (s.length() > 0) { 35 | // see whether word exists or not 36 | if (dictionary.containsKey(s)) { 37 | // if exist, count++ 38 | dictionary.put(s, dictionary.get(s) + 1); 39 | } else { 40 | // if not exist, initiate count of this word with 1 41 | dictionary.put(s, 1); 42 | } 43 | } 44 | s = ""; // reInit a empty word 45 | } 46 | in = fis.read(); 47 | } 48 | return dictionary; 49 | } catch (IOException e) { 50 | e.printStackTrace(); 51 | } finally { 52 | try { 53 | // you always have to close the I/O streams 54 | if (fis != null) { 55 | fis.close(); 56 | } 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | } 61 | return null; 62 | } 63 | } 64 | 65 | public static void main(String[] args) { 66 | // you can replace the filePath with yours 67 | CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); 68 | Map dictionary 69 | = cw.getDictionary(); // get the words dictionary: {word: frequency} 70 | 71 | // we change the map to list for convenient sort 72 | List> list = new ArrayList<>(dictionary.entrySet()); 73 | 74 | // sort by lambda valueComparator 75 | list.sort(Comparator.comparing(m -> m.getValue())); 76 | 77 | Scanner input = new Scanner(System.in); 78 | int k = input.nextInt(); 79 | while (k > list.size()) { 80 | System.out.println("Retype a number, your number is too large"); 81 | input = new Scanner(System.in); 82 | k = input.nextInt(); 83 | } 84 | for (int i = 0; i < k; i++) { 85 | System.out.println(list.get(list.size() - i - 1)); 86 | } 87 | input.close(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Others/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class TowerOfHanoi { 6 | 7 | public static void shift(int n, String startPole, String intermediatePole, String endPole) { 8 | // if n becomes zero the program returns thus ending the loop. 9 | if (n != 0) { 10 | // Shift function is called in recursion for swapping the n-1 disc from the startPole to the 11 | // intermediatePole 12 | shift(n - 1, startPole, endPole, intermediatePole); 13 | System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing 14 | // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole 15 | // to the endPole 16 | shift(n - 1, intermediatePole, startPole, endPole); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.print("Enter number of discs on Pole 1: "); 22 | Scanner scanner = new Scanner(System.in); 23 | int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1 24 | shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called 25 | scanner.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Others/TwoPointers.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * The two pointer technique is a useful tool to utilize when searching for 7 | * pairs in a sorted array. 8 | * 9 | *

10 | * link: https://www.geeksforgeeks.org/two-pointers-technique/ 11 | */ 12 | class TwoPointers { 13 | 14 | public static void main(String[] args) { 15 | int[] arr = {10, 20, 35, 50, 75, 80}; 16 | int key = 70; 17 | assert isPairedSum(arr, key); 18 | /* 20 + 60 == 70 */ 19 | 20 | arr = new int[]{1, 2, 3, 4, 5, 6, 7}; 21 | key = 13; 22 | assert isPairedSum(arr, key); 23 | /* 6 + 7 == 13 */ 24 | 25 | key = 14; 26 | assert !isPairedSum(arr, key); 27 | } 28 | 29 | /** 30 | * Given a sorted array arr (sorted in ascending order). Find if there 31 | * exists any pair of elements such that their sum is equal to key. 32 | * 33 | * @param arr the array contains elements 34 | * @param key the number to search 35 | * @return {@code true} if there exists a pair of elements, {@code false} 36 | * otherwise. 37 | */ 38 | private static boolean isPairedSum(int[] arr, int key) { 39 | /* array sorting is necessary for this algorithm to function correctly */ 40 | Arrays.sort(arr); 41 | int i = 0; 42 | /* index of first element */ 43 | int j = arr.length - 1; 44 | /* index of last element */ 45 | 46 | while (i < j) { 47 | if (arr[i] + arr[j] == key) { 48 | return true; 49 | } else if (arr[i] + arr[j] < key) { 50 | i++; 51 | } else { 52 | j--; 53 | } 54 | } 55 | return false; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms 🤓 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /Searches/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | import java.util.concurrent.ThreadLocalRandom; 8 | import java.util.stream.IntStream; 9 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 10 | 11 | /** 12 | * Binary search is one of the most popular algorithms The algorithm finds the 13 | * position of a target value within a sorted array 14 | * 15 | *

16 | * Worst-case performance O(log n) Best-case performance O(1) Average 17 | * performance O(log n) Worst-case space complexity O(1) 18 | * 19 | * @author Varun Upadhyay (https://github.com/varunu28) 20 | * @author Podshivalov Nikita (https://github.com/nikitap492) 21 | * @see SearchAlgorithm 22 | * @see IterativeBinarySearch 23 | */ 24 | class BinarySearch implements SearchAlgorithm { 25 | 26 | /** 27 | * @param array is an array where the element should be found 28 | * @param key is an element which should be found 29 | * @param is any comparable type 30 | * @return index of the element 31 | */ 32 | @Override 33 | public > int find(T[] array, T key) { 34 | return search(array, key, 0, array.length); 35 | } 36 | 37 | /** 38 | * This method implements the Generic Binary Search 39 | * 40 | * @param array The array to make the binary search 41 | * @param key The number you are looking for 42 | * @param left The lower bound 43 | * @param right The upper bound 44 | * @return the location of the key 45 | */ 46 | private > int search(T array[], T key, int left, int right) { 47 | if (right < left) { 48 | return -1; // this means that the key not found 49 | } 50 | // find median 51 | int median = (left + right) >>> 1; 52 | int comp = key.compareTo(array[median]); 53 | 54 | if (comp == 0) { 55 | return median; 56 | } else if (comp < 0) { 57 | return search(array, key, left, median - 1); 58 | } else { 59 | return search(array, key, median + 1, right); 60 | } 61 | } 62 | 63 | // Driver Program 64 | public static void main(String[] args) { 65 | // Just generate data 66 | Random r = ThreadLocalRandom.current(); 67 | 68 | int size = 100; 69 | int maxElement = 100000; 70 | 71 | Integer[] integers 72 | = IntStream.generate(() -> r.nextInt(maxElement)) 73 | .limit(size) 74 | .sorted() 75 | .boxed() 76 | .toArray(Integer[]::new); 77 | 78 | // The element that should be found 79 | int shouldBeFound = integers[r.nextInt(size - 1)]; 80 | 81 | BinarySearch search = new BinarySearch(); 82 | int atIndex = search.find(integers, shouldBeFound); 83 | 84 | System.out.println( 85 | format( 86 | "Should be found: %d. Found %d at index %d. An array length %d", 87 | shouldBeFound, integers[atIndex], atIndex, size)); 88 | 89 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 90 | System.out.println( 91 | format( 92 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Searches/BreadthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.searches.DepthFirstSearch.Node; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Objects; 8 | import java.util.Optional; 9 | 10 | /** 11 | * @author: caos321 12 | * @date: 31 October 2021 (Sunday) 13 | */ 14 | public class BreadthFirstSearch { 15 | 16 | public static Optional search(final Node node, final String name) { 17 | if (node.getName().equals(name)) { 18 | return Optional.of(node); 19 | } 20 | 21 | List queue = new ArrayList<>(node.getSubNodes()); 22 | 23 | while (!queue.isEmpty()) { 24 | final Node current = queue.get(0); 25 | 26 | if (current.getName().equals(name)) { 27 | return Optional.of(current); 28 | } 29 | 30 | queue.addAll(current.getSubNodes()); 31 | 32 | queue.remove(0); 33 | } 34 | 35 | return Optional.empty(); 36 | } 37 | 38 | public static void assertThat(final Object actual, final Object expected) { 39 | if (!Objects.equals(actual, expected)) { 40 | throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); 41 | } 42 | } 43 | 44 | public static void main(final String[] args) { 45 | final Node rootNode = new Node("A", List.of( 46 | new Node("B", List.of(new Node("D"), new Node("F", List.of( 47 | new Node("H"), new Node("I") 48 | )))), 49 | new Node("C", List.of(new Node("G"))), 50 | new Node("E") 51 | )); 52 | 53 | { 54 | final String expected = "I"; 55 | 56 | final Node result = search(rootNode, expected) 57 | .orElseThrow(() -> new AssertionError("Node not found!")); 58 | 59 | assertThat(result.getName(), expected); 60 | } 61 | 62 | { 63 | final String expected = "G"; 64 | 65 | final Node result = search(rootNode, expected) 66 | .orElseThrow(() -> new AssertionError("Node not found!")); 67 | 68 | assertThat(result.getName(), expected); 69 | } 70 | 71 | { 72 | final String expected = "E"; 73 | 74 | final Node result = search(rootNode, expected) 75 | .orElseThrow(() -> new AssertionError("Node not found!")); 76 | 77 | assertThat(result.getName(), expected); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Searches/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Objects; 6 | import java.util.Optional; 7 | 8 | /** 9 | * @author: caos321 10 | * @date: 31 October 2021 (Sunday) 11 | */ 12 | public class DepthFirstSearch { 13 | 14 | static class Node { 15 | 16 | private final String name; 17 | private final List subNodes; 18 | 19 | public Node(final String name) { 20 | this.name = name; 21 | this.subNodes = new ArrayList<>(); 22 | } 23 | 24 | public Node(final String name, final List subNodes) { 25 | this.name = name; 26 | this.subNodes = subNodes; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public List getSubNodes() { 34 | return subNodes; 35 | } 36 | } 37 | 38 | public static Optional search(final Node node, final String name) { 39 | if (node.getName().equals(name)) { 40 | return Optional.of(node); 41 | } 42 | 43 | return node.getSubNodes() 44 | .stream() 45 | .map(value -> search(value, name)) 46 | .flatMap(Optional::stream) 47 | .findAny(); 48 | } 49 | 50 | public static void assertThat(final Object actual, final Object expected) { 51 | if (!Objects.equals(actual, expected)) { 52 | throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual)); 53 | } 54 | } 55 | 56 | public static void main(final String[] args) { 57 | final Node rootNode = new Node("A", List.of( 58 | new Node("B", List.of(new Node("D"), new Node("F", List.of( 59 | new Node("H"), new Node("I") 60 | )))), 61 | new Node("C", List.of(new Node("G"))), 62 | new Node("E") 63 | )); 64 | 65 | { 66 | final String expected = "I"; 67 | 68 | final Node result = search(rootNode, expected) 69 | .orElseThrow(() -> new AssertionError("Node not found!")); 70 | 71 | assertThat(result.getName(), expected); 72 | } 73 | 74 | { 75 | final String expected = "G"; 76 | 77 | final Node result = search(rootNode, expected) 78 | .orElseThrow(() -> new AssertionError("Node not found!")); 79 | 80 | assertThat(result.getName(), expected); 81 | } 82 | 83 | { 84 | final String expected = "E"; 85 | 86 | final Node result = search(rootNode, expected) 87 | .orElseThrow(() -> new AssertionError("Node not found!")); 88 | 89 | assertThat(result.getName(), expected); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Searches/ExponentalSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | import java.util.concurrent.ThreadLocalRandom; 6 | import java.util.stream.IntStream; 7 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 8 | 9 | import static java.lang.String.format; 10 | 11 | class ExponentialSearch implements SearchAlgorithm { 12 | 13 | public static void main(String[] args) { 14 | Random r = ThreadLocalRandom.current(); 15 | 16 | int size = 100; 17 | int maxElement = 100000; 18 | 19 | Integer[] integers 20 | = IntStream.generate(() -> r.nextInt(maxElement)) 21 | .limit(size) 22 | .sorted() 23 | .boxed() 24 | .toArray(Integer[]::new); 25 | 26 | // The element that should be found 27 | int shouldBeFound = integers[r.nextInt(size - 1)]; 28 | 29 | ExponentialSearch search = new ExponentialSearch(); 30 | int atIndex = search.find(integers, shouldBeFound); 31 | 32 | System.out.println( 33 | format( 34 | "Should be found: %d. Found %d at index %d. An array length %d", 35 | shouldBeFound, integers[atIndex], atIndex, size)); 36 | 37 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 38 | System.out.println( 39 | format( 40 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 41 | 42 | } 43 | 44 | @Override 45 | public > int find(T[] array, T key) { 46 | if (array[0] == key) { 47 | return 0; 48 | } 49 | if (array[array.length - 1] == key) { 50 | return array.length; 51 | } 52 | 53 | int range = 1; 54 | 55 | while (range < array.length && array[range].compareTo(key) <= -1) { 56 | range = range * 2; 57 | } 58 | 59 | return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Searches/FibonacciSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 4 | 5 | /* 6 | * Fibonacci Search is a popular algorithm which finds the position of a target value in 7 | * a sorted array 8 | * 9 | * The time complexity for this search algorithm is O(log3(n)) 10 | * The space complexity for this search algorithm is O(1) 11 | * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) 12 | */ 13 | public class FibonacciSearch implements SearchAlgorithm { 14 | 15 | /** 16 | * @param array is a sorted array where the element has to be searched 17 | * @param key is an element whose position has to be found 18 | * @param is any comparable type 19 | * @return index of the element 20 | */ 21 | @Override 22 | public > int find(T[] array, T key) { 23 | int fibMinus1 = 1; 24 | int fibMinus2 = 0; 25 | int fibNumber = fibMinus1 + fibMinus2; 26 | int n = array.length; 27 | 28 | while (fibNumber < n) { 29 | fibMinus2 = fibMinus1; 30 | fibMinus1 = fibNumber; 31 | fibNumber = fibMinus2 + fibMinus1; 32 | } 33 | 34 | int offset = -1; 35 | 36 | while (fibNumber > 1) { 37 | int i = Math.min(offset + fibMinus2, n - 1); 38 | 39 | if (array[i].compareTo(key) < 0) { 40 | fibNumber = fibMinus1; 41 | fibMinus1 = fibMinus2; 42 | fibMinus2 = fibNumber - fibMinus1; 43 | offset = i; 44 | } else if (array[i].compareTo(key) > 0) { 45 | fibNumber = fibMinus2; 46 | fibMinus1 = fibMinus1 - fibMinus2; 47 | fibMinus2 = fibNumber - fibMinus1; 48 | } else { 49 | return i; 50 | } 51 | } 52 | 53 | if (fibMinus1 == 1 && array[offset + 1] == key) { 54 | return offset + 1; 55 | } 56 | 57 | return -1; 58 | } 59 | 60 | // Driver Program 61 | public static void main(String[] args) { 62 | Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; 63 | 64 | int size = integers.length; 65 | Integer shouldBeFound = 128; 66 | FibonacciSearch fsearch = new FibonacciSearch(); 67 | int atIndex = fsearch.find(integers, shouldBeFound); 68 | 69 | System.out.println( 70 | "Should be found: " + shouldBeFound + ". Found " + integers[atIndex] + " at index " + atIndex + ". An array length " + size); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Searches/HowManyTimesRotated.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.*; 4 | 5 | /* 6 | Problem Statement: 7 | Given an array, find out how many times it has to been rotated 8 | from its initial sorted position. 9 | Input-Output: 10 | Eg. [11,12,15,18,2,5,6,8] 11 | It has been rotated: 4 times 12 | (One rotation means putting the first element to the end) 13 | Note: The array cannot contain duplicates 14 | 15 | Logic: 16 | The position of the minimum element will give the number of times the array has been rotated 17 | from its initial sorted position. 18 | Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. 19 | Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N). 20 | If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i] a[mid - 1] && a[mid] < a[mid + 1]) { 52 | high = mid + 1; 53 | } else if (a[mid] > a[mid - 1] && a[mid] > a[mid + 1]) { 54 | low = mid - 1; 55 | } 56 | } 57 | 58 | return mid; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Searches/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | import java.util.stream.IntStream; 8 | 9 | /** 10 | * Interpolation search algorithm implementation 11 | * 12 | *

13 | * Worst-case performance O(n) Best-case performance O(1) Average performance 14 | * O(log(log(n))) if the elements are uniformly distributed if not O(n) 15 | * Worst-case space complexity O(1) 16 | * 17 | * @author Podshivalov Nikita (https://github.com/nikitap492) 18 | */ 19 | class InterpolationSearch { 20 | 21 | /** 22 | * @param array is a sorted array 23 | * @param key is a value what shoulb be found in the array 24 | * @return an index if the array contains the key unless -1 25 | */ 26 | public int find(int array[], int key) { 27 | // Find indexes of two corners 28 | int start = 0, end = (array.length - 1); 29 | 30 | // Since array is sorted, an element present 31 | // in array must be in range defined by corner 32 | while (start <= end && key >= array[start] && key <= array[end]) { 33 | // Probing the position with keeping 34 | // uniform distribution in mind. 35 | int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); 36 | 37 | // Condition of target found 38 | if (array[pos] == key) { 39 | return pos; 40 | } 41 | 42 | // If key is larger, key is in upper part 43 | if (array[pos] < key) { 44 | start = pos + 1; 45 | } // If key is smaller, x is in lower part 46 | else { 47 | end = pos - 1; 48 | } 49 | } 50 | return -1; 51 | } 52 | 53 | // Driver method 54 | public static void main(String[] args) { 55 | Random r = new Random(); 56 | int size = 100; 57 | int maxElement = 100000; 58 | int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); 59 | 60 | // the element that should be found 61 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 62 | 63 | InterpolationSearch search = new InterpolationSearch(); 64 | int atIndex = search.find(integers, shouldBeFound); 65 | 66 | System.out.println( 67 | String.format( 68 | "Should be found: %d. Found %d at index %d. An array length %d", 69 | shouldBeFound, integers[atIndex], atIndex, size)); 70 | 71 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 72 | System.out.println( 73 | format( 74 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Searches/IterativeBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | import java.util.stream.Stream; 8 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 9 | 10 | /** 11 | * Binary search is one of the most popular algorithms This class represents 12 | * iterative version {@link BinarySearch} Iterative binary search is likely to 13 | * have lower constant factors because it doesn't involve the overhead of 14 | * manipulating the call stack. But in java the recursive version can be 15 | * optimized by the compiler to this version. 16 | * 17 | *

18 | * Worst-case performance O(log n) Best-case performance O(1) Average 19 | * performance O(log n) Worst-case space complexity O(1) 20 | * 21 | * @author Gabriele La Greca : https://github.com/thegabriele97 22 | * @author Podshivalov Nikita (https://github.com/nikitap492) 23 | * @see SearchAlgorithm 24 | * @see BinarySearch 25 | */ 26 | public final class IterativeBinarySearch implements SearchAlgorithm { 27 | 28 | /** 29 | * This method implements an iterative version of binary search algorithm 30 | * 31 | * @param array a sorted array 32 | * @param key the key to search in array 33 | * @return the index of key in the array or -1 if not found 34 | */ 35 | @Override 36 | public > int find(T[] array, T key) { 37 | int l, r, k, cmp; 38 | 39 | l = 0; 40 | r = array.length - 1; 41 | 42 | while (l <= r) { 43 | k = (l + r) >>> 1; 44 | cmp = key.compareTo(array[k]); 45 | 46 | if (cmp == 0) { 47 | return k; 48 | } else if (cmp < 0) { 49 | r = --k; 50 | } else { 51 | l = ++k; 52 | } 53 | } 54 | 55 | return -1; 56 | } 57 | 58 | // Only a main method for test purpose 59 | public static void main(String[] args) { 60 | Random r = new Random(); 61 | int size = 100; 62 | int maxElement = 100000; 63 | Integer[] integers 64 | = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); 65 | 66 | // the element that should be found 67 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 68 | 69 | IterativeBinarySearch search = new IterativeBinarySearch(); 70 | int atIndex = search.find(integers, shouldBeFound); 71 | 72 | System.out.println( 73 | String.format( 74 | "Should be found: %d. Found %d at index %d. An array length %d", 75 | shouldBeFound, integers[atIndex], atIndex, size)); 76 | 77 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 78 | System.out.println( 79 | format( 80 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Searches/IterativeTernarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | import java.util.stream.Stream; 8 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 9 | 10 | /** 11 | * A iterative version of a ternary search algorithm This is better way to 12 | * implement the ternary search, because a recursive version adds some overhead 13 | * to a stack. But in java the compile can transform the recursive version to 14 | * iterative implicitly, so there are no much differences between these two 15 | * algorithms 16 | * 17 | *

18 | * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average 19 | * performance Θ(log3(N)) Worst-case space complexity O(1) 20 | * 21 | * @author Podshivalov Nikita (https://github.com/nikitap492) 22 | * @see SearchAlgorithm 23 | * @see TernarySearch 24 | * @since 2018-04-13 25 | */ 26 | public class IterativeTernarySearch implements SearchAlgorithm { 27 | 28 | @Override 29 | public > int find(T[] array, T key) { 30 | int left = 0; 31 | int right = array.length - 1; 32 | 33 | while (right > left) { 34 | 35 | int leftCmp = array[left].compareTo(key); 36 | int rightCmp = array[right].compareTo(key); 37 | if (leftCmp == 0) { 38 | return left; 39 | } 40 | if (rightCmp == 0) { 41 | return right; 42 | } 43 | 44 | int leftThird = left + (right - left) / 3 + 1; 45 | int rightThird = right - (right - left) / 3 - 1; 46 | 47 | if (array[leftThird].compareTo(key) <= 0) { 48 | left = leftThird; 49 | } else { 50 | right = rightThird; 51 | } 52 | } 53 | 54 | return -1; 55 | } 56 | 57 | public static void main(String[] args) { 58 | // just generate data 59 | Random r = new Random(); 60 | int size = 100; 61 | int maxElement = 100000; 62 | Integer[] integers 63 | = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); 64 | 65 | // the element that should be found 66 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 67 | 68 | IterativeTernarySearch search = new IterativeTernarySearch(); 69 | int atIndex = search.find(integers, shouldBeFound); 70 | 71 | System.out.println( 72 | format( 73 | "Should be found: %d. Found %d at index %d. An array length %d", 74 | shouldBeFound, integers[atIndex], atIndex, size)); 75 | 76 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 77 | System.out.println( 78 | format( 79 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Searches/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 4 | 5 | public class JumpSearch implements SearchAlgorithm { 6 | 7 | public static void main(String[] args) { 8 | JumpSearch jumpSearch = new JumpSearch(); 9 | Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 10 | for (int i = 0; i < array.length; i++) { 11 | assert jumpSearch.find(array, i) == i; 12 | } 13 | assert jumpSearch.find(array, -1) == -1; 14 | assert jumpSearch.find(array, 11) == -1; 15 | } 16 | 17 | /** 18 | * Jump Search algorithm implements 19 | * 20 | * @param array the array contains elements 21 | * @param key to be searched 22 | * @return index of {@code key} if found, otherwise -1 23 | */ 24 | @Override 25 | public > int find(T[] array, T key) { 26 | int length = array.length; 27 | /* length of array */ 28 | int blockSize = (int) Math.sqrt(length); 29 | /* block size to be jumped */ 30 | 31 | int limit = blockSize; 32 | while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { 33 | limit = Math.min(limit + blockSize, array.length - 1); 34 | } 35 | 36 | for (int i = limit - blockSize; i <= limit; i++) { 37 | if (array[i] == key) { 38 | /* execute linear search */ 39 | return i; 40 | } 41 | } 42 | return -1; 43 | /* not found */ 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Searches/LinearSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.Random; 4 | import java.util.stream.Stream; 5 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 6 | 7 | /** 8 | * Linear search is the easiest search algorithm It works with sorted and 9 | * unsorted arrays (an binary search works only with sorted array) This 10 | * algorithm just compares all elements of an array to find a value 11 | * 12 | *

13 | * Worst-case performance O(n) Best-case performance O(1) Average performance 14 | * O(n) Worst-case space complexity 15 | * 16 | * @author Varun Upadhyay (https://github.com/varunu28) 17 | * @author Podshivalov Nikita (https://github.com/nikitap492) 18 | * @see BinarySearch 19 | * @see SearchAlgorithm 20 | */ 21 | public class LinearSearch implements SearchAlgorithm { 22 | 23 | /** 24 | * Generic Linear search method 25 | * 26 | * @param array List to be searched 27 | * @param value Key being searched for 28 | * @return Location of the key 29 | */ 30 | @Override 31 | public > int find(T[] array, T value) { 32 | for (int i = 0; i < array.length; i++) { 33 | if (array[i].compareTo(value) == 0) { 34 | return i; 35 | } 36 | } 37 | return -1; 38 | } 39 | 40 | public static void main(String[] args) { 41 | // just generate data 42 | Random r = new Random(); 43 | int size = 200; 44 | int maxElement = 100; 45 | Integer[] integers 46 | = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new); 47 | 48 | // the element that should be found 49 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 50 | 51 | LinearSearch search = new LinearSearch(); 52 | int atIndex = search.find(integers, shouldBeFound); 53 | 54 | System.out.println( 55 | String.format( 56 | "Should be found: %d. Found %d at index %d. An array length %d", 57 | shouldBeFound, integers[atIndex], atIndex, size)); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Searches/LinearSearchThread.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.Scanner; 4 | 5 | public class LinearSearchThread { 6 | public static void main(String[] args) { 7 | int[] list = new int[200]; 8 | for (int j = 0; j < list.length; j++) { 9 | list[j] = (int) (Math.random() * 100); 10 | } 11 | for (int y : list) { 12 | System.out.print(y + " "); 13 | } 14 | System.out.println(); 15 | System.out.print("Enter number to search for: "); 16 | Scanner in = new Scanner(System.in); 17 | int x = in.nextInt(); 18 | Searcher t = new Searcher(list, 0, 50, x); 19 | Searcher t1 = new Searcher(list, 50, 100, x); 20 | Searcher t2 = new Searcher(list, 100, 150, x); 21 | Searcher t3 = new Searcher(list, 150, 200, x); 22 | t.start(); 23 | t1.start(); 24 | t2.start(); 25 | t3.start(); 26 | try { 27 | t.join(); 28 | t1.join(); 29 | t2.join(); 30 | t3.join(); 31 | } catch (InterruptedException e) { 32 | } 33 | boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); 34 | System.out.println("Found = " + found); 35 | } 36 | } 37 | 38 | class Searcher extends Thread { 39 | private final int[] arr; 40 | private final int left, right; 41 | private final int x; 42 | private boolean found; 43 | 44 | Searcher(int[] arr, int left, int right, int x) { 45 | this.arr = arr; 46 | this.left = left; 47 | this.right = right; 48 | this.x = x; 49 | } 50 | 51 | @Override 52 | public void run() { 53 | int k = left; 54 | found = false; 55 | while (k < right && !found) { 56 | if (arr[k++] == x) { 57 | found = true; 58 | } 59 | } 60 | } 61 | 62 | boolean getResult() { 63 | return found; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Searches/LowerBound.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Random; 6 | import java.util.concurrent.ThreadLocalRandom; 7 | import java.util.stream.IntStream; 8 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 9 | 10 | /** 11 | * The LowerBound method is used to return an index pointing to the first 12 | * element in the range [first, last) which has a value not less than val, i.e. 13 | * the index of the next smallest number just greater than or equal to that 14 | * number. If there are multiple values that are equal to val it returns the 15 | * index of the first such value. 16 | * 17 | *

18 | * This is an extension of BinarySearch. 19 | * 20 | *

21 | * Worst-case performance O(log n) Best-case performance O(1) Average 22 | * performance O(log n) Worst-case space complexity O(1) 23 | * 24 | * @author Pratik Padalia (https://github.com/15pratik) 25 | * @see SearchAlgorithm 26 | * @see BinarySearch 27 | */ 28 | class LowerBound implements SearchAlgorithm { 29 | 30 | // Driver Program 31 | public static void main(String[] args) { 32 | // Just generate data 33 | Random r = ThreadLocalRandom.current(); 34 | 35 | int size = 100; 36 | int maxElement = 100000; 37 | 38 | Integer[] integers 39 | = IntStream.generate(() -> r.nextInt(maxElement)) 40 | .limit(size) 41 | .sorted() 42 | .boxed() 43 | .toArray(Integer[]::new); 44 | 45 | // The element for which the lower bound is to be found 46 | int val = integers[r.nextInt(size - 1)] + 1; 47 | 48 | LowerBound search = new LowerBound(); 49 | int atIndex = search.find(integers, val); 50 | 51 | System.out.println( 52 | format( 53 | "Val: %d. Lower Bound Found %d at index %d. An array length %d", 54 | val, integers[atIndex], atIndex, size)); 55 | 56 | boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val; 57 | System.out.println( 58 | format( 59 | "Lower Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck)); 60 | } 61 | 62 | /** 63 | * @param array is an array where the LowerBound value is to be found 64 | * @param key is an element for which the LowerBound is to be found 65 | * @param is any comparable type 66 | * @return index of the LowerBound element 67 | */ 68 | @Override 69 | public > int find(T[] array, T key) { 70 | return search(array, key, 0, array.length - 1); 71 | } 72 | 73 | /** 74 | * This method implements the Generic Binary Search 75 | * 76 | * @param array The array to make the binary search 77 | * @param key The number you are looking for 78 | * @param left The lower bound 79 | * @param right The upper bound 80 | * @return the location of the key 81 | */ 82 | private > int search(T[] array, T key, int left, int right) { 83 | if (right <= left) { 84 | return left; 85 | } 86 | 87 | // find median 88 | int median = (left + right) >>> 1; 89 | int comp = key.compareTo(array[median]); 90 | 91 | if (comp == 0) { 92 | return median; 93 | } else if (comp < 0) { 94 | // median position can be a possible solution 95 | return search(array, key, left, median); 96 | } else { 97 | // key we are looking is greater, so we must look on the right of median position 98 | return search(array, key, median + 1, right); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Searches/PerfectBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | class PerfectBinarySearch { 4 | 5 | static int binarySearch(int[] arr, int target) { 6 | int low = 0; 7 | int high = arr.length - 1; 8 | 9 | while (low <= high) { 10 | int mid = (low + high) / 2; 11 | 12 | if (arr[mid] == target) { 13 | return mid; 14 | } else if (arr[mid] > target) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); 25 | int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 26 | assert BinarySearch.binarySearch(array, -1) == -1; 27 | assert BinarySearch.binarySearch(array, 11) == -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Searches/QuickSelect.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.*; 4 | 5 | /** 6 | * An implementation of the Quickselect algorithm as described 7 | * here. 8 | */ 9 | public final class QuickSelect { 10 | 11 | /** 12 | * Selects the {@code n}-th largest element of {@code list}, i.e. the element that would 13 | * be at index n if the list was sorted. 14 | *

15 | * Calling this function might change the order of elements in {@code list}. 16 | * 17 | * @param list the list of elements 18 | * @param n the index 19 | * @param the type of list elements 20 | * @return the n-th largest element in the list 21 | * @throws IndexOutOfBoundsException if n is less than 0 or greater or equal to 22 | * the number of elements in the list 23 | * @throws IllegalArgumentException if the list is empty 24 | * @throws NullPointerException if {@code list} is null 25 | */ 26 | public static > T select(List list, int n) { 27 | Objects.requireNonNull(list, "The list of elements must not be null."); 28 | 29 | if (list.size() == 0) { 30 | String msg = "The list of elements must not be empty."; 31 | throw new IllegalArgumentException(msg); 32 | } 33 | 34 | if (n < 0) { 35 | String msg = "The index must not be negative."; 36 | throw new IndexOutOfBoundsException(msg); 37 | } 38 | 39 | if (n >= list.size()) { 40 | String msg = "The index must be less than the number of elements."; 41 | throw new IndexOutOfBoundsException(msg); 42 | } 43 | 44 | int index = selectIndex(list, n); 45 | return list.get(index); 46 | } 47 | 48 | private static > int selectIndex(List list, int n) { 49 | return selectIndex(list, 0, list.size() - 1, n); 50 | } 51 | 52 | private static > int selectIndex( 53 | List list, 54 | int left, 55 | int right, 56 | int n 57 | ) { 58 | while (true) { 59 | if (left == right) 60 | return left; 61 | int pivotIndex = pivot(list, left, right); 62 | pivotIndex = partition(list, left, right, pivotIndex, n); 63 | if (n == pivotIndex) { 64 | return n; 65 | } else if (n < pivotIndex) { 66 | right = pivotIndex - 1; 67 | } else { 68 | left = pivotIndex + 1; 69 | } 70 | } 71 | } 72 | 73 | private static > int partition( 74 | List list, 75 | int left, 76 | int right, 77 | int pivotIndex, 78 | int n 79 | ) { 80 | T pivotValue = list.get(pivotIndex); 81 | Collections.swap(list, pivotIndex, right); 82 | int storeIndex = left; 83 | 84 | for (int i = left; i < right; i++) { 85 | if (list.get(i).compareTo(pivotValue) < 0) { 86 | Collections.swap(list, storeIndex, i); 87 | storeIndex++; 88 | } 89 | } 90 | 91 | int storeIndexEq = storeIndex; 92 | 93 | for (int i = storeIndex; i < right; i++) { 94 | if (list.get(i).compareTo(pivotValue) == 0) { 95 | Collections.swap(list, storeIndexEq, i); 96 | storeIndexEq++; 97 | } 98 | } 99 | 100 | Collections.swap(list, right, storeIndexEq); 101 | 102 | return (n < storeIndex) 103 | ? storeIndex 104 | : Math.min(n, storeIndexEq); 105 | } 106 | 107 | private static > int pivot( 108 | List list, 109 | int left, 110 | int right 111 | ) { 112 | if (right - left < 5) { 113 | return partition5(list, left, right); 114 | } 115 | 116 | for (int i = left; i < right; i += 5) { 117 | int subRight = i + 4; 118 | if (subRight > right) { 119 | subRight = right; 120 | } 121 | int median5 = partition5(list, i, subRight); 122 | int rightIndex = left + (i - left) / 5; 123 | Collections.swap(list, median5, rightIndex); 124 | } 125 | 126 | int mid = (right - left) / 10 + left + 1; 127 | int rightIndex = left + (right - left) / 5; 128 | return selectIndex(list, left, rightIndex, mid); 129 | } 130 | 131 | private static > int partition5( 132 | List list, 133 | int left, 134 | int right 135 | ) { 136 | List ts = list.subList(left, right); 137 | ts.sort(Comparator.naturalOrder()); 138 | return (left + right) >>> 1; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Searches/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Searches/SaddlebackSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Program to perform Saddleback Search Given a sorted 2D array(elements are 7 | * sorted across every row and column, assuming ascending order) of size n*m we 8 | * can search a given element in O(n+m) 9 | * 10 | *

11 | * we start from bottom left corner if the current element is greater than the 12 | * given element then we move up else we move right Sample Input: 5 5 13 | * ->Dimensions -10 -5 -3 4 9 -6 -2 0 5 10 -4 -1 1 6 12 2 3 7 8 13 100 120 130 14 | * 140 150 140 ->element to be searched output: 4 3 // first value is row, 15 | * second one is column 16 | * 17 | * @author Nishita Aggarwal 18 | */ 19 | public class SaddlebackSearch { 20 | 21 | /** 22 | * This method performs Saddleback Search 23 | * 24 | * @param arr The **Sorted** array in which we will search the element. 25 | * @param row the current row. 26 | * @param col the current column. 27 | * @param key the element that we want to search for. 28 | * @return The index(row and column) of the element if found. Else returns 29 | * -1 -1. 30 | */ 31 | private static int[] find(int arr[][], int row, int col, int key) { 32 | 33 | // array to store the answer row and column 34 | int ans[] = {-1, -1}; 35 | if (row < 0 || col >= arr[row].length) { 36 | return ans; 37 | } 38 | if (arr[row][col] == key) { 39 | ans[0] = row; 40 | ans[1] = col; 41 | return ans; 42 | } // if the current element is greater than the given element then we move up 43 | else if (arr[row][col] > key) { 44 | return find(arr, row - 1, col, key); 45 | } 46 | // else we move right 47 | return find(arr, row, col + 1, key); 48 | } 49 | 50 | /** 51 | * Main method 52 | * 53 | * @param args Command line arguments 54 | */ 55 | public static void main(String[] args) { 56 | // TODO Auto-generated method stub 57 | Scanner sc = new Scanner(System.in); 58 | int arr[][]; 59 | int i, j, rows = sc.nextInt(), col = sc.nextInt(); 60 | arr = new int[rows][col]; 61 | for (i = 0; i < rows; i++) { 62 | for (j = 0; j < col; j++) { 63 | arr[i][j] = sc.nextInt(); 64 | } 65 | } 66 | int ele = sc.nextInt(); 67 | // we start from bottom left corner 68 | int ans[] = find(arr, rows - 1, 0, ele); 69 | System.out.println(ans[0] + " " + ans[1]); 70 | sc.close(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Searches/SquareRootBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Given an integer x, find the square root of x. If x is not a perfect square, 7 | * then return floor(√x). 8 | *

9 | * For example, if x = 5, The answer should be 2 which is the floor value of √5. 10 | *

11 | * The approach that will be used for solving the above problem is not going to 12 | * be a straight forward Math.sqrt(). Instead we will be using Binary Search to 13 | * find the square root of a number in the most optimised way. 14 | * 15 | * @author sahil 16 | */ 17 | public class SquareRootBinarySearch { 18 | 19 | /** 20 | * This is the driver method. 21 | * 22 | * @param args Command line arguments 23 | */ 24 | public static void main(String args[]) { 25 | Scanner sc = new Scanner(System.in); 26 | System.out.print("Enter a number you want to calculate square root of : "); 27 | int num = sc.nextInt(); 28 | long ans = squareRoot(num); 29 | System.out.println("The square root is : " + ans); 30 | } 31 | 32 | /** 33 | * This function calculates the floor of square root of a number. We use 34 | * Binary Search algorithm to calculate the square root in a more optimised 35 | * way. 36 | * 37 | * @param num Number 38 | * @return answer 39 | */ 40 | private static long squareRoot(long num) { 41 | if (num == 0 || num == 1) { 42 | return num; 43 | } 44 | long l = 1; 45 | long r = num; 46 | long ans = 0; 47 | while (l <= r) { 48 | long mid = l + (r - l) / 2; 49 | if (mid == num / mid) { 50 | return mid; 51 | } else if (mid < num / mid) { 52 | ans = mid; 53 | l = mid + 1; 54 | } else { 55 | r = mid - 1; 56 | } 57 | } 58 | return ans; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Searches/TernarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Arrays; 6 | import java.util.Random; 7 | import java.util.stream.Stream; 8 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 9 | 10 | /** 11 | * A ternary search algorithm is a technique in computer science for finding the 12 | * minimum or maximum of a unimodal function The algorithm determines either 13 | * that the minimum or maximum cannot be in the first third of the domain or 14 | * that it cannot be in the last third of the domain, then repeats on the 15 | * remaining third. 16 | * 17 | *

18 | * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average 19 | * performance Θ(log3(N)) Worst-case space complexity O(1) 20 | * 21 | * @author Podshivalov Nikita (https://github.com/nikitap492) 22 | * @see SearchAlgorithm 23 | * @see IterativeBinarySearch 24 | */ 25 | public class TernarySearch implements SearchAlgorithm { 26 | 27 | /** 28 | * @param arr The **Sorted** array in which we will search the element. 29 | * @param value The value that we want to search for. 30 | * @return The index of the element if found. Else returns -1. 31 | */ 32 | @Override 33 | public > int find(T[] arr, T value) { 34 | return ternarySearch(arr, value, 0, arr.length - 1); 35 | } 36 | 37 | /** 38 | * @param arr The **Sorted** array in which we will search the element. 39 | * @param key The value that we want to search for. 40 | * @param start The starting index from which we will start Searching. 41 | * @param end The ending index till which we will Search. 42 | * @return Returns the index of the Element if found. Else returns -1. 43 | */ 44 | private > int ternarySearch(T[] arr, T key, int start, int end) { 45 | if (start > end) { 46 | return -1; 47 | } 48 | /* First boundary: add 1/3 of length to start */ 49 | int mid1 = start + (end - start) / 3; 50 | /* Second boundary: add 2/3 of length to start */ 51 | int mid2 = start + 2 * (end - start) / 3; 52 | 53 | if (key.compareTo(arr[mid1]) == 0) { 54 | return mid1; 55 | } else if (key.compareTo(arr[mid2]) == 0) { 56 | return mid2; 57 | } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { 58 | return ternarySearch(arr, key, start, --mid1); 59 | } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { 60 | return ternarySearch(arr, key, ++mid2, end); 61 | } /* Search middle (1/3)rd part of the array */ else { 62 | return ternarySearch(arr, key, mid1, mid2); 63 | } 64 | } 65 | 66 | public static void main(String[] args) { 67 | // just generate data 68 | Random r = new Random(); 69 | int size = 100; 70 | int maxElement = 100000; 71 | Integer[] integers 72 | = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); 73 | 74 | // the element that should be found 75 | Integer shouldBeFound = integers[r.nextInt(size - 1)]; 76 | 77 | TernarySearch search = new TernarySearch(); 78 | int atIndex = search.find(integers, shouldBeFound); 79 | 80 | System.out.println( 81 | format( 82 | "Should be found: %d. Found %d at index %d. An array length %d", 83 | shouldBeFound, integers[atIndex], atIndex, size)); 84 | 85 | int toCheck = Arrays.binarySearch(integers, shouldBeFound); 86 | System.out.println( 87 | format( 88 | "Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Searches/UnionFind.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import java.util.*; 4 | 5 | public class UnionFind { 6 | 7 | private int[] p; 8 | private int[] r; 9 | 10 | public UnionFind(int n) { 11 | p = new int[n]; 12 | r = new int[n]; 13 | 14 | for (int i = 0; i < n; i++) { 15 | p[i] = i; 16 | } 17 | } 18 | 19 | public int find(int i) { 20 | int parent = p[i]; 21 | 22 | if (i == parent) { 23 | return i; 24 | } 25 | 26 | return p[i] = find(parent); 27 | } 28 | 29 | public void union(int x, int y) { 30 | int r0 = find(x); 31 | int r1 = find(y); 32 | 33 | if (r1 == r0) { 34 | return; 35 | } 36 | 37 | if (r[r0] > r[r1]) { 38 | p[r1] = r0; 39 | } else if (r[r1] > r[r0]) { 40 | p[r0] = r1; 41 | } else { 42 | p[r1] = r0; 43 | r[r0]++; 44 | } 45 | } 46 | 47 | public int count() { 48 | List parents = new ArrayList(); 49 | for (int i = 0; i < p.length; i++) { 50 | if (!parents.contains(find(i))) { 51 | parents.add(find(i)); 52 | } 53 | } 54 | return parents.size(); 55 | } 56 | 57 | public String toString() { 58 | return "p " + Arrays.toString(p) + " r " + Arrays.toString(r) + "\n"; 59 | } 60 | 61 | // Tests 62 | public static void main(String[] args) { 63 | UnionFind uf = new UnionFind(5); 64 | System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):"); 65 | System.out.println(uf); 66 | 67 | uf.union(1, 2); 68 | System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):"); 69 | System.out.println(uf); 70 | 71 | uf.union(3, 4); 72 | System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); 73 | System.out.println(uf); 74 | 75 | uf.find(4); 76 | System.out.println("find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); 77 | System.out.println(uf); 78 | 79 | System.out.println("count (should print '3'):"); 80 | System.out.println(uf.count()); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Searches/UpperBound.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static java.lang.String.format; 4 | 5 | import java.util.Random; 6 | import java.util.concurrent.ThreadLocalRandom; 7 | import java.util.stream.IntStream; 8 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 9 | 10 | /** 11 | * The UpperBound method is used to return an index pointing to the first 12 | * element in the range [first, last) which has a value greater than val, or the 13 | * last index if no such element exists i.e. the index of the next smallest 14 | * number just greater than that number. If there are multiple values that are 15 | * equal to val it returns the index of the first such value. 16 | * 17 | *

18 | * This is an extension of BinarySearch. 19 | * 20 | *

21 | * Worst-case performance O(log n) Best-case performance O(1) Average 22 | * performance O(log n) Worst-case space complexity O(1) 23 | * 24 | * @author Pratik Padalia (https://github.com/15pratik) 25 | * @see SearchAlgorithm 26 | * @see BinarySearch 27 | */ 28 | class UpperBound implements SearchAlgorithm { 29 | 30 | // Driver Program 31 | public static void main(String[] args) { 32 | // Just generate data 33 | Random r = ThreadLocalRandom.current(); 34 | 35 | int size = 100; 36 | int maxElement = 100000; 37 | 38 | Integer[] integers 39 | = IntStream.generate(() -> r.nextInt(maxElement)) 40 | .limit(size) 41 | .sorted() 42 | .boxed() 43 | .toArray(Integer[]::new); 44 | 45 | // The element for which the upper bound is to be found 46 | int val = integers[r.nextInt(size - 1)] + 1; 47 | 48 | UpperBound search = new UpperBound(); 49 | int atIndex = search.find(integers, val); 50 | 51 | System.out.println( 52 | format( 53 | "Val: %d. Upper Bound Found %d at index %d. An array length %d", 54 | val, integers[atIndex], atIndex, size)); 55 | 56 | boolean toCheck = integers[atIndex] > val || integers[size - 1] < val; 57 | System.out.println( 58 | format( 59 | "Upper Bound found at an index: %d. Is greater or max element: %b", atIndex, toCheck)); 60 | } 61 | 62 | /** 63 | * @param array is an array where the UpperBound value is to be found 64 | * @param key is an element for which the UpperBound is to be found 65 | * @param is any comparable type 66 | * @return index of the UpperBound element 67 | */ 68 | @Override 69 | public > int find(T[] array, T key) { 70 | return search(array, key, 0, array.length - 1); 71 | } 72 | 73 | /** 74 | * This method implements the Generic Binary Search 75 | * 76 | * @param array The array to make the binary search 77 | * @param key The number you are looking for 78 | * @param left The lower bound 79 | * @param right The upper bound 80 | * @return the location of the key 81 | */ 82 | private > int search(T[] array, T key, int left, int right) { 83 | if (right <= left) { 84 | return left; 85 | } 86 | 87 | // find median 88 | int median = (left + right) >>> 1; 89 | int comp = key.compareTo(array[median]); 90 | 91 | if (comp < 0) { 92 | // key is smaller, median position can be a possible solution 93 | return search(array, key, left, median); 94 | } else { 95 | // key we are looking is greater, so we must look on the right of median position 96 | return search(array, key, median + 1, right); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Strings/Alphabetical.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Alphabetical order is a system whereby character strings are placed in order 5 | * based on the position of the characters in the conventional ordering of an 6 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 7 | */ 8 | class Alphabetical { 9 | 10 | public static void main(String[] args) { 11 | assert !isAlphabetical("123abc"); 12 | assert isAlphabetical("aBC"); 13 | assert isAlphabetical("abc"); 14 | assert !isAlphabetical("xyzabc"); 15 | assert isAlphabetical("abcxyz"); 16 | } 17 | 18 | /** 19 | * Check if a string is alphabetical order or not 20 | * 21 | * @param s a string 22 | * @return {@code true} if given string is alphabetical order, otherwise 23 | * {@code false} 24 | */ 25 | public static boolean isAlphabetical(String s) { 26 | s = s.toLowerCase(); 27 | for (int i = 0; i < s.length() - 1; ++i) { 28 | if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class CharactersSame { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | assert isAllCharactersSame(""); 10 | assert !isAllCharactersSame("aab"); 11 | assert isAllCharactersSame("aaa"); 12 | assert isAllCharactersSame("11111"); 13 | } 14 | 15 | /** 16 | * check if all the characters of a string are same 17 | * 18 | * @param s the string to check 19 | * @return {@code true} if all characters of a string are same, otherwise 20 | * {@code false} 21 | */ 22 | public static boolean isAllCharactersSame(String s) { 23 | for (int i = 1, length = s.length(); i < length; ++i) { 24 | if (s.charAt(i) != s.charAt(0)) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Strings/CheckAnagrams.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Two strings are anagrams if they are made of the same letters arranged 8 | * differently (ignoring the case). 9 | */ 10 | public class CheckAnagrams { 11 | 12 | public static void main(String[] args) { 13 | assert isAnagrams("Silent", "Listen"); 14 | assert isAnagrams("This is a string", "Is this a string"); 15 | assert !isAnagrams("There", "Their"); 16 | } 17 | 18 | /** 19 | * Check if two strings are anagrams or not 20 | * 21 | * @param s1 the first string 22 | * @param s2 the second string 23 | * @return {@code true} if two string are anagrams, otherwise {@code false} 24 | */ 25 | public static boolean isAnagrams(String s1, String s2) { 26 | int l1 = s1.length(); 27 | int l2 = s2.length(); 28 | s1 = s1.toLowerCase(); 29 | s2 = s2.toLowerCase(); 30 | Map charAppearances = new HashMap<>(); 31 | 32 | for (int i = 0; i < l1; i++) { 33 | char c = s1.charAt(i); 34 | int numOfAppearances = charAppearances.getOrDefault(c, 0); 35 | charAppearances.put(c, numOfAppearances + 1); 36 | } 37 | 38 | for (int i = 0; i < l2; i++) { 39 | char c = s2.charAt(i); 40 | if (!charAppearances.containsKey(c)) { 41 | return false; 42 | } 43 | charAppearances.put(c, charAppearances.get(c) - 1); 44 | } 45 | 46 | for (int cnt : charAppearances.values()) { 47 | if (cnt != 0) { 48 | return false; 49 | } 50 | } 51 | return true; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Strings/CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Vowel Count is a system whereby character strings are placed in order based 9 | * on the position of the characters in the conventional ordering of an 10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 11 | */ 12 | public class CheckVowels { 13 | private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); 14 | 15 | /** 16 | * Check if a string is has vowels or not 17 | * 18 | * @param input a string 19 | * @return {@code true} if given string has vowels, otherwise {@code false} 20 | */ 21 | public static boolean hasVowels(String input) { 22 | return countVowels(input) > 0; 23 | } 24 | 25 | /** 26 | * count the number of vowels 27 | * 28 | * @param input a string prints the count of vowels 29 | */ 30 | public static int countVowels(String input) { 31 | if (input == null) { 32 | return 0; 33 | } 34 | int cnt = 0; 35 | for (char c : input.toLowerCase().toCharArray()) { 36 | if (VOWELS.contains(c)) { 37 | ++cnt; 38 | } 39 | } 40 | return cnt; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Strings/List_all_Possible_Words_From_Phone_Digits.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.*; 4 | 5 | public class List_all_Possible_Words_From_Phone_Digits { 6 | 7 | static Character[][] numberToCharMap; 8 | 9 | private static List printWords(int[] numbers, 10 | int len, 11 | int numIndex, 12 | String s) { 13 | if (len == numIndex) { 14 | return new ArrayList<>(Collections.singleton(s)); 15 | } 16 | 17 | List stringList = new ArrayList<>(); 18 | 19 | for (int i = 0; 20 | i < numberToCharMap[numbers[numIndex]].length; i++) { 21 | String sCopy 22 | = String.copyValueOf(s.toCharArray()); 23 | sCopy = sCopy.concat( 24 | numberToCharMap[numbers[numIndex]][i].toString()); 25 | stringList.addAll(printWords(numbers, len, 26 | numIndex + 1, 27 | sCopy)); 28 | } 29 | return stringList; 30 | } 31 | 32 | private static void printWords(int[] numbers) { 33 | generateNumberToCharMap(); 34 | List stringList 35 | = printWords(numbers, numbers.length, 0, ""); 36 | stringList.stream().forEach(System.out::println); 37 | } 38 | 39 | private static void generateNumberToCharMap() { 40 | numberToCharMap = new Character[10][5]; 41 | numberToCharMap[0] = new Character[]{'\0'}; 42 | numberToCharMap[1] = new Character[]{'\0'}; 43 | numberToCharMap[2] = new Character[]{'a', 'b', 'c'}; 44 | numberToCharMap[3] = new Character[]{'d', 'e', 'f'}; 45 | numberToCharMap[4] = new Character[]{'g', 'h', 'i'}; 46 | numberToCharMap[5] = new Character[]{'j', 'k', 'l'}; 47 | numberToCharMap[6] = new Character[]{'m', 'n', 'o'}; 48 | numberToCharMap[7] = new Character[]{'p', 'q', 'r', 's'}; 49 | numberToCharMap[8] = new Character[]{'t', 'u', 'v'}; 50 | numberToCharMap[9] = new Character[]{'w', 'x', 'y', 'z'}; 51 | } 52 | 53 | // Driver code 54 | public static void main(String[] args) { 55 | int number[] = {2, 3, 4}; 56 | printWords(number); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Strings/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | // Longest Palindromic Substring 4 | import java.util.Scanner; 5 | 6 | class LongestPalindromicSubstring { 7 | 8 | public static void main(String[] args) { 9 | Solution s = new Solution(); 10 | String str = ""; 11 | Scanner sc = new Scanner(System.in); 12 | System.out.print("Enter the string: "); 13 | str = sc.nextLine(); 14 | System.out.println("Longest substring is : " + s.longestPalindrome(str)); 15 | } 16 | } 17 | 18 | class Solution { 19 | 20 | public String longestPalindrome(String s) { 21 | if (s == null || s.length() == 0) { 22 | return ""; 23 | } 24 | int n = s.length(); 25 | String maxStr = ""; 26 | for (int i = 0; i < n; ++i) { 27 | for (int j = i; j < n; ++j) { 28 | if (isValid(s, i, j) == true) { 29 | if (j - i + 1 > maxStr.length()) { // update maxStr 30 | maxStr = s.substring(i, j + 1); 31 | } 32 | } 33 | } 34 | } 35 | return maxStr; 36 | } 37 | 38 | private boolean isValid(String s, int lo, int hi) { 39 | int n = hi - lo + 1; 40 | for (int i = 0; i < n / 2; ++i) { 41 | if (s.charAt(lo + i) != s.charAt(hi - i)) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Strings/Lower.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Lower { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toLowerCase(s).equals(s.toLowerCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to lower case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to lowercase. 20 | */ 21 | public static String toLowerCase(String s) { 22 | char[] values = s.toCharArray(); 23 | for (int i = 0; i < values.length; ++i) { 24 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { 25 | values[i] = Character.toLowerCase(values[i]); 26 | } 27 | } 28 | return new String(values); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Strings/Palindrome.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Wikipedia: https://en.wikipedia.org/wiki/Palindrome 5 | */ 6 | class Palindrome { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | String[] palindromes = {null, "", "aba", "123321"}; 13 | for (String s : palindromes) { 14 | assert isPalindrome(s) && isPalindromeRecursion(s) && isPalindrome1(s); 15 | } 16 | 17 | String[] notPalindromes = {"abb", "abc", "abc123"}; 18 | for (String s : notPalindromes) { 19 | assert !isPalindrome(s) && !isPalindromeRecursion(s) && !isPalindrome1(s); 20 | } 21 | } 22 | 23 | /** 24 | * Check if a string is palindrome string or not 25 | * 26 | * @param s a string to check 27 | * @return {@code true} if given string is palindrome, otherwise 28 | * {@code false} 29 | */ 30 | public static boolean isPalindrome(String s) { 31 | return (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString()); 32 | } 33 | 34 | /** 35 | * Check if a string is palindrome string or not using recursion 36 | * 37 | * @param s a string to check 38 | * @return {@code true} if given string is palindrome, otherwise 39 | * {@code false} 40 | */ 41 | public static boolean isPalindromeRecursion(String s) { 42 | if (s == null || s.length() <= 1) { 43 | return true; 44 | } 45 | 46 | if (s.charAt(0) != s.charAt(s.length() - 1)) { 47 | return false; 48 | } 49 | 50 | return isPalindrome(s.substring(1, s.length() - 1)); 51 | } 52 | 53 | /** 54 | * Check if a string is palindrome string or not another way 55 | * 56 | * @param s a string to check 57 | * @return {@code true} if given string is palindrome, otherwise 58 | * {@code false} 59 | */ 60 | public static boolean isPalindrome1(String s) { 61 | if (s == null || s.length() <= 1) { 62 | return true; 63 | } 64 | for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { 65 | if (s.charAt(i) != s.charAt(j)) { 66 | return false; 67 | } 68 | } 69 | return true; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Strings/Pangram.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Wikipedia: https://en.wikipedia.org/wiki/Pangram 5 | */ 6 | public class Pangram { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | assert isPangram("The quick brown fox jumps over the lazy dog"); 13 | assert !isPangram("The quick brown fox jumps over the azy dog"); 14 | /* not exists l character */ 15 | } 16 | 17 | /** 18 | * Check if a string is a pangram string or not 19 | * 20 | * @param s string to check 21 | * @return {@code true} if given string is pangram, otherwise {@code false} 22 | */ 23 | public static boolean isPangram(String s) { 24 | boolean[] marked = new boolean[26]; 25 | /* by default all letters don't exists */ 26 | char[] values = s.toCharArray(); 27 | for (char value : values) { 28 | if (Character.isLetter(value)) { 29 | int index = Character.isUpperCase(value) ? value - 'A' : value - 'a'; 30 | marked[index] = true; 31 | /* mark current character exists */ 32 | } 33 | } 34 | 35 | for (boolean b : marked) { 36 | if (!b) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Strings/PermuteString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /* 4 | Backtracking algorithm used in the program:- 5 | 6 | >>Fix a character in the first position and swap the rest of the character with the first character. 7 | Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with 8 | A, B and C respectively. 9 | >>Repeat step 1 for the rest of the characters like fixing second character B and so on. 10 | >>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again, 11 | and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB. 12 | >>Repeat these steps for BAC and CBA, to get all the permutations. 13 | */ 14 | public class PermuteString { 15 | 16 | //Function for swapping the characters at position I with character at position j 17 | public static String swapString(String a, int i, int j) { 18 | char[] b = a.toCharArray(); 19 | char ch; 20 | ch = b[i]; 21 | b[i] = b[j]; 22 | b[j] = ch; 23 | return String.valueOf(b); 24 | } 25 | 26 | public static void main(String[] args) { 27 | String str = "ABC"; 28 | int len = str.length(); 29 | System.out.println("All the permutations of the string are: "); 30 | generatePermutation(str, 0, len); 31 | } 32 | 33 | //Function for generating different permutations of the string 34 | public static void generatePermutation(String str, int start, int end) { 35 | //Prints the permutations 36 | if (start == end - 1) { 37 | System.out.println(str); 38 | } else { 39 | for (int i = start; i < end; i++) { 40 | //Swapping the string by fixing a character 41 | str = swapString(str, start, i); 42 | //Recursively calling function generatePermutation() for rest of the characters 43 | generatePermutation(str, start + 1, end); 44 | //Backtracking and swapping the characters again. 45 | str = swapString(str, start, i); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Strings/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using different version 5 | */ 6 | public class ReverseString { 7 | 8 | public static void main(String[] args) { 9 | assert reverse("abc123").equals("321cba"); 10 | assert reverse2("abc123").equals("321cba"); 11 | } 12 | 13 | /** 14 | * easiest way to reverses the string str and returns it 15 | * 16 | * @param str string to be reversed 17 | * @return reversed string 18 | */ 19 | public static String reverse(String str) { 20 | return new StringBuilder(str).reverse().toString(); 21 | } 22 | 23 | /** 24 | * second way to reverses the string str and returns it 25 | * 26 | * @param str string to be reversed 27 | * @return reversed string 28 | */ 29 | public static String reverse2(String str) { 30 | 31 | if (str == null || str.isEmpty()) { 32 | return str; 33 | } 34 | 35 | char[] value = str.toCharArray(); 36 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) { 37 | char temp = value[i]; 38 | value[i] = value[j]; 39 | value[j] = temp; 40 | } 41 | return new String(value); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Strings/Rotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Given a string, moving several characters in front of the string to the end 5 | * of the string. For example, move the two characters'a' and 'b' in front of 6 | * the string "abcdef" to the end of the string, so that the original string 7 | * becomes the string "cdefab" 8 | */ 9 | public class Rotation { 10 | 11 | public static void main(String[] args) { 12 | assert rotation("abcdef", 2).equals("cdefab"); 13 | 14 | char[] values = "abcdef".toCharArray(); 15 | rotation(values, 2); 16 | assert new String(values).equals("cdefab"); 17 | } 18 | 19 | /** 20 | * Move {@code n} characters in front of given string to the end of string 21 | * time complexity: O(n) space complexity: O(n) 22 | * 23 | * @param s given string 24 | * @param n the total characters to be moved 25 | * @return string after rotation 26 | */ 27 | public static String rotation(String s, int n) { 28 | return s.substring(n) + s.substring(0, n); 29 | } 30 | 31 | /** 32 | * Move {@code n} characters in front of given character array to the end of 33 | * array time complexity: O(n) space complexity: O(1) 34 | * 35 | * @param values given character array 36 | * @param n the total characters to be moved 37 | */ 38 | public static void rotation(char[] values, int n) { 39 | reverse(values, 0, n - 1); 40 | reverse(values, n, values.length - 1); 41 | reverse(values, 0, values.length - 1); 42 | } 43 | 44 | /** 45 | * Reverse character array 46 | * 47 | * @param values character array 48 | * @param from begin index of given array 49 | * @param to end index of given array 50 | */ 51 | public static void reverse(char[] values, int from, int to) { 52 | while (from < to) { 53 | char temp = values[from]; 54 | values[from] = values[to]; 55 | values[to] = temp; 56 | from++; 57 | to--; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Strings/Upper.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Upper { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toUpperCase(s).equals(s.toUpperCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to upper case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to uppercase. 20 | */ 21 | public static String toUpperCase(String s) { 22 | if (s == null || "".equals(s)) { 23 | return s; 24 | } 25 | char[] values = s.toCharArray(); 26 | for (int i = 0; i < values.length; ++i) { 27 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { 28 | values[i] = Character.toUpperCase(values[i]); 29 | } 30 | } 31 | return new String(values); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Strings/WordLadder.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.List; 4 | import java.util.Arrays; 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | import java.util.HashSet; 8 | 9 | /* 10 | **Problem Statement:** 11 | A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: 12 | 13 | Every adjacent pair of words differs by a single letter. 14 | Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. 15 | sk == endWord 16 | Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. 17 | 18 | **Example 1:** 19 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 20 | Output: 5 21 | Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. 22 | 23 | **Example 2:** 24 | Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] 25 | Output: 0 26 | Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. 27 | 28 | **Constraints:** 29 | 1 <= beginWord.length <= 10 30 | endWord.length == beginWord.length 31 | 1 <= wordList.length <= 5000 32 | wordList[i].length == beginWord.length 33 | beginWord, endWord, and wordList[i] consist of lowercase English letters. 34 | beginWord != endWord 35 | All the words in wordList are unique. 36 | */ 37 | class WordLadder { 38 | 39 | /** 40 | * Driver Code 41 | */ 42 | public static void main(String[] args) { 43 | 44 | String beginWord = "hit"; 45 | String endWord = "cog"; 46 | String words[] = {"hot", "dot", "dog", "lot", "log", "cog"}; 47 | List wordList = Arrays.asList(words); 48 | 49 | System.out.println("Ladder Length: " + ladderLength(beginWord, endWord, wordList)); 50 | } 51 | 52 | /** 53 | * This function finds the ladderLength 54 | * 55 | * @param beginWord: Starting word of the ladder 56 | * @param endWord: Ending word of the ladder 57 | * @param wordList: This list contains the words which needs to be included 58 | * in ladder. 59 | * @return ladderLength: This function will return the ladderLength(level) 60 | * if the endword is there. Otherwise, will return the length as 0. 61 | */ 62 | public static int ladderLength(String beginWord, String endWord, List wordList) { 63 | HashSet set = new HashSet(); 64 | for (String word : wordList) { 65 | set.add(word); 66 | } 67 | 68 | if (!set.contains(endWord)) { 69 | return 0; 70 | } 71 | 72 | Queue queue = new LinkedList(); 73 | queue.offer(beginWord); 74 | int level = 1; 75 | 76 | while (!queue.isEmpty()) { 77 | int size = queue.size(); 78 | for (int i = 0; i < size; i++) { 79 | String curr = queue.poll(); 80 | char[] words_chars = curr.toCharArray(); 81 | for (int j = 0; j < words_chars.length; j++) { 82 | char original_chars = words_chars[j]; 83 | for (char c = 'a'; c <= 'z'; c++) { 84 | if (words_chars[j] == c) { 85 | continue; 86 | } 87 | words_chars[j] = c; 88 | String new_word = String.valueOf(words_chars); 89 | if (new_word.equals(endWord)) { 90 | return level + 1; 91 | } 92 | if (set.contains(new_word)) { 93 | set.remove(new_word); 94 | queue.offer(new_word); 95 | } 96 | } 97 | words_chars[j] = original_chars; 98 | } 99 | } 100 | level++; 101 | } 102 | return 0; 103 | } 104 | } 105 | --------------------------------------------------------------------------------