diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml new file mode 100644 index 000000000000..325fa04502af --- /dev/null +++ b/.github/workflows/update_directory_md.yml @@ -0,0 +1,67 @@ +# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push +name: update_directory_md +on: [push] +jobs: + update_directory_md: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + - uses: actions/setup-python@master + - name: update_directory_md + shell: python + run: | + import os + from typing import Iterator + + URL_BASE = "https://github.com/TheAlgorithms/Java/blob/master" + g_output = [] + + + def good_filepaths(top_dir: str = ".") -> Iterator[str]: + for dirpath, dirnames, filenames in os.walk(top_dir): + dirnames[:] = [d for d in dirnames if d[0] not in "._"] + for filename in filenames: + if os.path.splitext(filename)[1].lower() == ".java": + yield os.path.join(dirpath, filename).lstrip("./") + + + def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + + def print_path(old_path: str, new_path: str) -> str: + global g_output + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ')}") + return new_path + + + def build_directory_md(top_dir: str = ".") -> str: + global g_output + old_path = "" + for filepath in sorted(good_filepaths(), key=str.lower): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " "))[0] + g_output.append(f"{md_prefix(indent)} [{filename}]({url})") + return "\n".join(g_output) + + + with open("DIRECTORY.md", "w") as out_file: + out_file.write(build_directory_md(".") + "\n") + + - name: Update DIRECTORY.md + run: | + cat DIRECTORY.md + git config --global user.name github-actions + git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git add DIRECTORY.md + git commit -am "updating DIRECTORY.md" || true + git push --force origin HEAD:$GITHUB_REF || true diff --git a/Conversions/AnyBaseToAnyBase.java b/Conversions/AnyBaseToAnyBase.java index cfcf0fe9ad61..2cef99260e6b 100644 --- a/Conversions/AnyBaseToAnyBase.java +++ b/Conversions/AnyBaseToAnyBase.java @@ -52,6 +52,7 @@ public static void main(String[] args) { } } System.out.println(base2base(n, b1, b2)); + in.close(); } /** diff --git a/Conversions/AnytoAny.java b/Conversions/AnytoAny.java index 5fc744a9936c..1bc115404696 100644 --- a/Conversions/AnytoAny.java +++ b/Conversions/AnytoAny.java @@ -24,6 +24,7 @@ public static void main(String[] args) { dec /= db; } System.out.println(dn); + scn.close(); } } diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index 2c8d3218fdfe..cd84486ae812 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -5,7 +5,7 @@ /** * This class converts a Decimal number to a Binary number * - * @author Unknown + * */ class DecimalToBinary { @@ -53,6 +53,7 @@ public static void bitwiseConversion() { n >>= 1; } System.out.println("\tBinary number: " + b); + input.close(); } } diff --git a/Conversions/DecimalToHexaDecimal.java b/Conversions/DecimalToHexaDecimal.java index c9c4e434417c..3d0351dd0122 100644 --- a/Conversions/DecimalToHexaDecimal.java +++ b/Conversions/DecimalToHexaDecimal.java @@ -1,5 +1,6 @@ package Conversions; +//hex = [0 - 9] -> [A - F] class DecimalToHexaDecimal { private static final int sizeOfIntInHalfBytes = 8; private static final int numberOfBitsInAHalfByte = 4; diff --git a/Conversions/DecimalToOctal.java b/Conversions/DecimalToOctal.java index 017ab33321b5..98c9f1bb0c48 100644 --- a/Conversions/DecimalToOctal.java +++ b/Conversions/DecimalToOctal.java @@ -5,7 +5,7 @@ /** * This class converts Decimal numbers to Octal Numbers * - * @author Unknown + * */ public class DecimalToOctal { /** @@ -13,6 +13,8 @@ public class DecimalToOctal { * * @param args Command line Arguments */ + + //enter in a decimal value to get Octal output public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, k, d, s = 0, c = 0; diff --git a/Conversions/HexToOct.java b/Conversions/HexToOct.java index a46debfe9992..2807735f72fb 100644 --- a/Conversions/HexToOct.java +++ b/Conversions/HexToOct.java @@ -64,7 +64,6 @@ public static void main(String args[]) { // convert decimal to octal octalnum = decimal2octal(decnum); System.out.println("Number in octal: " + octalnum); - - + scan.close(); } } diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java index 8a79e9b4f00c..091822ce0cb4 100644 --- a/Conversions/HexaDecimalToBinary.java +++ b/Conversions/HexaDecimalToBinary.java @@ -1,5 +1,7 @@ package Conversions; +//Hex [0-9],[A-F] -> Binary [0,1] + public class HexaDecimalToBinary { private final int LONG_BITS = 8; @@ -9,7 +11,7 @@ public void convert(String numHex) { int conHex = Integer.parseInt(numHex, 16); // Hex a Binary: String binary = Integer.toBinaryString(conHex); - // Presentation: + // Output: System.out.println(numHex + " = " + completeDigits(binary)); } diff --git a/Conversions/HexaDecimalToDecimal.java b/Conversions/HexaDecimalToDecimal.java index 533009b8ae16..14b0d94d76c2 100644 --- a/Conversions/HexaDecimalToDecimal.java +++ b/Conversions/HexaDecimalToDecimal.java @@ -34,7 +34,7 @@ public static void main(String args[]) { and it returns the decimal form in the variable dec_output. */ System.out.println("Number in Decimal: " + dec_output); - + scan.close(); } } diff --git a/Conversions/IntegerToRoman.java b/Conversions/IntegerToRoman.java index e979eb536336..8886ef4ad016 100644 --- a/Conversions/IntegerToRoman.java +++ b/Conversions/IntegerToRoman.java @@ -1,9 +1,29 @@ package Conversions; +/** + * Converting Integers into Roman Numerals + * + *('I', 1); + *('IV',4); + *('V', 5); + *('IV',9); + *('X', 10); + *('XL',40; + *('L', 50); + *('XC',90); + *('C', 100); + *('D', 500); + *('M', 1000); + * + */ + + public class IntegerToRoman { private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; + //Value must be > 0 + public static String integerToRoman(int num) { if (num <= 0) { return ""; diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java index 2cefc92002ca..dd8d877109b5 100644 --- a/Conversions/OctalToHexadecimal.java +++ b/Conversions/OctalToHexadecimal.java @@ -59,6 +59,7 @@ public static void main(String args[]) { // Pass the decimla number to function and get converted Hex form of the number String hex = DecimalToHex(decimal); System.out.println("The Hexadecimal equivalant is: " + hex); + input.close(); } } diff --git a/Conversions/RomanToInteger.java b/Conversions/RomanToInteger.java index 7d6e0650ab46..4563ce4a4a72 100644 --- a/Conversions/RomanToInteger.java +++ b/Conversions/RomanToInteger.java @@ -13,6 +13,7 @@ public class RomanToInteger { put('D', 500); put('M', 1000); }}; + //Roman Number = Roman Numerals /** * This function convert Roman number into Integer diff --git a/DIRECTORY.md b/DIRECTORY.md new file mode 100644 index 000000000000..a8052bc883b7 --- /dev/null +++ b/DIRECTORY.md @@ -0,0 +1,202 @@ + +## ciphers + * [AES](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AES.java) + * [AESEncryption](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AESEncryption.java) + * [Caesar](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Caesar.java) + * [ColumnarTranspositionCipher](https://github.com/TheAlgorithms/Java/blob/master/ciphers/ColumnarTranspositionCipher.java) + * [RSA](https://github.com/TheAlgorithms/Java/blob/master/ciphers/RSA.java) + * [SimpleSubstitutionCipher](https://github.com/TheAlgorithms/Java/blob/master/ciphers/SimpleSubstitutionCipher.java) + * [Vigenere](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Vigenere.java) + +## Conversions + * [AnyBaseToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnyBaseToAnyBase.java) + * [AnyBaseToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnyBaseToDecimal.java) + * [AnytoAny](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnytoAny.java) + * [BinaryToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToDecimal.java) + * [BinaryToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToHexadecimal.java) + * [BinaryToOctal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToOctal.java) + * [DecimalToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToAnyBase.java) + * [DecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToBinary.java) + * [DecimalToHexaDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToHexaDecimal.java) + * [DecimalToOctal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToOctal.java) + * [HexaDecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexaDecimalToBinary.java) + * [HexaDecimalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexaDecimalToDecimal.java) + * [HexToOct](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexToOct.java) + * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/Conversions/IntegerToRoman.java) + * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/OctalToDecimal.java) + * [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/OctalToHexadecimal.java) + * [RomanToInteger](https://github.com/TheAlgorithms/Java/blob/master/Conversions/RomanToInteger.java) + +## DataStructures + * Bags + * [Bag](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Bags/Bag.java) + * Buffers + * [CircularBuffer](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Buffers/CircularBuffer.java) + * Graphs + * [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/BellmanFord.java) + * [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/ConnectedComponent.java) + * [Cycles](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Cycles.java) + * [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/FloydWarshall.java) + * [Graphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Graphs.java) + * [MatrixGraphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/MatrixGraphs.java) + * [PrimMST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/PrimMST.java) + * HashMap + * Hashing + * [HashMap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/HashMap.java) + * [LinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/LinkedList.java) + * [Main](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Main.java) + * [Node](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Node.java) + * Heaps + * [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/EmptyHeapException.java) + * [Heap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/Heap.java) + * [HeapElement](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/HeapElement.java) + * [MaxHeap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MaxHeap.java) + * [MinHeap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MinHeap.java) + * [MinPriorityQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MinPriorityQueue.java) + * Lists + * [CircleLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/CircleLinkedList.java) + * [CursorLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/CursorLinkedList.java) + * [DoublyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/DoublyLinkedList.java) + * [Merge K SortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/Merge_K_SortedLinkedlist.java) + * [MergeSortedArrayList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/MergeSortedArrayList.java) + * [SinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/SinglyLinkedList.java) + * Queues + * [GenericArrayListQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/GenericArrayListQueue.java) + * [LinkedQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/LinkedQueue.java) + * [PriorityQueues](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/PriorityQueues.java) + * [Queues](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/Queues.java) + * Stacks + * [BalancedBrackets](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/BalancedBrackets.java) + * [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/DecimalToAnyUsingStack.java) + * [NodeStack](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/NodeStack.java) + * [StackArray](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackArray.java) + * [StackArrayList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackArrayList.java) + * [StackOfLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackOfLinkedList.java) + * Trees + * [AVLTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/AVLTree.java) + * [BinaryTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/BinaryTree.java) + * [GenericTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/GenericTree.java) + * [LevelOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/LevelOrderTraversal.java) + * [LevelOrderTraversalQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/LevelOrderTraversalQueue.java) + * [PrintTopViewofTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/PrintTopViewofTree.java) + * [RedBlackBST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/RedBlackBST.java) + * [TreeTraversal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/TreeTraversal.java) + * [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/TrieImp.java) + * [ValidBSTOrNot](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/ValidBSTOrNot.java) + +## divideconquer + * [ClosestPair](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/ClosestPair.java) + * [SkylineAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/SkylineAlgorithm.java) + +## DynamicProgramming + * [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/CoinChange.java) + * [EditDistance](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/EditDistance.java) + * [EggDropping](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/EggDropping.java) + * [Fibonacci](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/Fibonacci.java) + * [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/FordFulkerson.java) + * [KadaneAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/KadaneAlgorithm.java) + * [Knapsack](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/Knapsack.java) + * [LevenshteinDistance](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LevenshteinDistance.java) + * [LongestCommonSubsequence](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestCommonSubsequence.java) + * [LongestIncreasingSubsequence](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestIncreasingSubsequence.java) + * [LongestValidParentheses](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestValidParentheses.java) + * [MatrixChainMultiplication](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/MatrixChainMultiplication.java) + * [RodCutting](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/RodCutting.java) + +## Maths + * [AbsoluteMax](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMax.java) + * [AbsoluteMin](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMin.java) + * [AbsoluteValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteValue.java) + * [Factorial](https://github.com/TheAlgorithms/Java/blob/master/Maths/Factorial.java) + * [FactorialRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FactorialRecursion.java) + * [FibonacciNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/FibonacciNumber.java) + * [FindMax](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMax.java) + * [FindMaxRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMaxRecursion.java) + * [FindMin](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMin.java) + * [FindMinRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMinRecursion.java) + * [GCD](https://github.com/TheAlgorithms/Java/blob/master/Maths/GCD.java) + * [GCDRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/GCDRecursion.java) + * [MaxValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/MaxValue.java) + * [MinValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/MinValue.java) + * [PalindromeNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/PalindromeNumber.java) + * [ParseInteger](https://github.com/TheAlgorithms/Java/blob/master/Maths/ParseInteger.java) + * [PerfectNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/PerfectNumber.java) + * [Pow](https://github.com/TheAlgorithms/Java/blob/master/Maths/Pow.java) + * [PowRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/PowRecursion.java) + * [PrimeCheck](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeCheck.java) + +## MinimizingLateness + * [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/MinimizingLateness/MinimizingLateness.java) + +## Misc + * [heap sort](https://github.com/TheAlgorithms/Java/blob/master/Misc/heap_sort.java) + * [MedianOfRunningArray](https://github.com/TheAlgorithms/Java/blob/master/Misc/MedianOfRunningArray.java) + * [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/Misc/PalindromePrime.java) + +## Others + * [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java) + * [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java) + * [BestFit](https://github.com/TheAlgorithms/Java/blob/master/Others/BestFit.java) + * [BrianKernighanAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/BrianKernighanAlgorithm.java) + * [CountChar](https://github.com/TheAlgorithms/Java/blob/master/Others/CountChar.java) + * [CountWords](https://github.com/TheAlgorithms/Java/blob/master/Others/CountWords.java) + * [CRC32](https://github.com/TheAlgorithms/Java/blob/master/Others/CRC32.java) + * [CRCAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/CRCAlgorithm.java) + * [Dijkstra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkstra.java) + * [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/Others/EulersFunction.java) + * [FibToN](https://github.com/TheAlgorithms/Java/blob/master/Others/FibToN.java) + * [FirstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/FirstFit.java) + * [FloydTriangle](https://github.com/TheAlgorithms/Java/blob/master/Others/FloydTriangle.java) + * [GuassLegendre](https://github.com/TheAlgorithms/Java/blob/master/Others/GuassLegendre.java) + * [InsertDeleteInArray](https://github.com/TheAlgorithms/Java/blob/master/Others/InsertDeleteInArray.java) + * [KMP](https://github.com/TheAlgorithms/Java/blob/master/Others/KMP.java) + * [Krishnamurthy](https://github.com/TheAlgorithms/Java/blob/master/Others/Krishnamurthy.java) + * [LinearCongruentialGenerator](https://github.com/TheAlgorithms/Java/blob/master/Others/LinearCongruentialGenerator.java) + * [LowestBasePalindrome](https://github.com/TheAlgorithms/Java/blob/master/Others/LowestBasePalindrome.java) + * [Palindrome](https://github.com/TheAlgorithms/Java/blob/master/Others/Palindrome.java) + * [PasswordGen](https://github.com/TheAlgorithms/Java/blob/master/Others/PasswordGen.java) + * [PerlinNoise](https://github.com/TheAlgorithms/Java/blob/master/Others/PerlinNoise.java) + * [PowerOfTwoOrNot](https://github.com/TheAlgorithms/Java/blob/master/Others/PowerOfTwoOrNot.java) + * [QueueUsingTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/Others/QueueUsingTwoStacks.java) + * [RemoveDuplicateFromString](https://github.com/TheAlgorithms/Java/blob/master/Others/RemoveDuplicateFromString.java) + * [ReturnSubsequence](https://github.com/TheAlgorithms/Java/blob/master/Others/ReturnSubsequence.java) + * [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java) + * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseString.java) + * [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/Others/RootPrecision.java) + * [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/Others/SieveOfEratosthenes.java) + * [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java) + * [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java) + * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/Others/StackPostfixNotation.java) + * [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/Others/TopKWords.java) + * [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/Others/TowerOfHanoi.java) + * [WorstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/WorstFit.java) + +## Searches + * [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java) + * [InterpolationSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/InterpolationSearch.java) + * [IterativeBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/IterativeBinarySearch.java) + * [IterativeTernarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/IterativeTernarySearch.java) + * [JumpSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/JumpSearch.java) + * [LinearSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/LinearSearch.java) + * [SaddlebackSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/SaddlebackSearch.java) + * [SearchAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Searches/SearchAlgorithm.java) + * [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/TernarySearch.java) + +## Sorts + * [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java) + * [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java) + * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java) + * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java) + * [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CountingSort.java) + * [CycleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CycleSort.java) + * [GnomeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/GnomeSort.java) + * [HeapSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/HeapSort.java) + * [InsertionSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/InsertionSort.java) + * [MergeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/MergeSort.java) + * [PancakeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/PancakeSort.java) + * [QuickSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/QuickSort.java) + * [RadixSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/RadixSort.java) + * [SelectionSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SelectionSort.java) + * [ShellSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/ShellSort.java) + * [SortAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortAlgorithm.java) + * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java) diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java index 717cb2803031..6dffede9e606 100644 --- a/DataStructures/Graphs/BellmanFord.java +++ b/DataStructures/Graphs/BellmanFord.java @@ -1,3 +1,5 @@ +package DataStructures.Graphs; + import java.util.*; class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have @@ -98,6 +100,7 @@ public void go()//Interactive run for understanding the class first time. Assume System.out.println(); } } + sc.close(); } /** * @param source Starting vertex diff --git a/DataStructures/HashMap/Hashing/Main.java b/DataStructures/HashMap/Hashing/Main.java index 66f65c1d9064..340f0760b2e5 100644 --- a/DataStructures/HashMap/Hashing/Main.java +++ b/DataStructures/HashMap/Hashing/Main.java @@ -42,6 +42,7 @@ public static void main(String[] args) { return; } } + In.close(); } } } \ No newline at end of file diff --git a/DataStructures/Queues/LinkedQueue.java b/DataStructures/Queues/LinkedQueue.java index 1c85937b9a06..dac13dcaaad6 100644 --- a/DataStructures/Queues/LinkedQueue.java +++ b/DataStructures/Queues/LinkedQueue.java @@ -1,4 +1,4 @@ -package DataStructures; +package DataStructures.Queues; import java.util.NoSuchElementException; diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java index c598bb8fcba1..616e6a1e1548 100644 --- a/DataStructures/Stacks/NodeStack.java +++ b/DataStructures/Stacks/NodeStack.java @@ -1,3 +1,4 @@ +package DataStructures.Stacks; /** * Implementation of a stack using nodes. * Unlimited size, no arraylist. diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java index 88da42cd3dcb..4365dc448d2d 100644 --- a/DataStructures/Stacks/StackArray.java +++ b/DataStructures/Stacks/StackArray.java @@ -1,3 +1,5 @@ +package DataStructures.Stacks; + /** * This class implements a Stack using a regular array. *

diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java index afc804440403..666b9ea99055 100644 --- a/DataStructures/Stacks/StackArrayList.java +++ b/DataStructures/Stacks/StackArrayList.java @@ -1,3 +1,5 @@ +package DataStructures.Stacks; + import java.util.ArrayList; /** diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java index 5a2b8fa08258..60d8a1b0f7a0 100644 --- a/DataStructures/Stacks/StackOfLinkedList.java +++ b/DataStructures/Stacks/StackOfLinkedList.java @@ -1,5 +1,7 @@ package DataStructures.Stacks; +import java.util.NoSuchElementException; + /** * @author Varun Upadhyay (https://github.com/varunu28) */ diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java index 75d3af18e56b..6ef4b5ada325 100644 --- a/DataStructures/Trees/BinaryTree.java +++ b/DataStructures/Trees/BinaryTree.java @@ -145,12 +145,19 @@ else if (temp.left != null && temp.right != null) { successor.left.parent = successor; //If the successor has a right child, the child's grandparent is it's new parent - if (successor.right != null && successor.parent != temp) { - successor.right.parent = successor.parent; - successor.parent.left = successor.right; - successor.right = temp.right; - successor.right.parent = successor; + if(successor.parent!=temp){ + if(successor.right!=null){ + successor.right.parent = successor.parent; + successor.parent.left = successor.right; + successor.right = temp.right; + successor.right.parent = successor; + }else{ + successor.parent.left=null; + successor.right=temp.right; + successor.right.parent=successor; + } } + if (temp == root) { successor.parent = null; root = successor; diff --git a/DataStructures/Trees/RedBlackBST.java b/DataStructures/Trees/RedBlackBST.java index 97a88e9a43de..197c96321975 100644 --- a/DataStructures/Trees/RedBlackBST.java +++ b/DataStructures/Trees/RedBlackBST.java @@ -309,6 +309,7 @@ public void insertDemo() { printTreepre(root); break; } + scan.close(); } public void deleteDemo() { diff --git a/DynamicProgramming/EditDistance.java b/DynamicProgramming/EditDistance.java index 210469b84108..20cb8803a754 100644 --- a/DynamicProgramming/EditDistance.java +++ b/DynamicProgramming/EditDistance.java @@ -74,5 +74,6 @@ public static void main(String[] args) { //ans stores the final Edit Distance between the two strings int ans = minDistance(s1, s2); System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); + input.close(); } } diff --git a/DynamicProgramming/Fibonacci.java b/DynamicProgramming/Fibonacci.java index 112a014a378a..89be0836f6af 100644 --- a/DynamicProgramming/Fibonacci.java +++ b/DynamicProgramming/Fibonacci.java @@ -22,6 +22,7 @@ public static void main(String[] args) { System.out.println(fibMemo(n)); System.out.println(fibBotUp(n)); System.out.println(fibOptimized(n)); + sc.close(); } /** diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java index 2b07e040db13..c8296518590d 100644 --- a/DynamicProgramming/LongestIncreasingSubsequence.java +++ b/DynamicProgramming/LongestIncreasingSubsequence.java @@ -17,6 +17,7 @@ public static void main(String[] args) { } System.out.println(LIS(ar)); + sc.close(); } private static int upperBound(int[] ar, int l, int r, int key) { diff --git a/Maths/AbsoluteMax.java b/Maths/AbsoluteMax.java index 18634bc3582f..f454f8ae003d 100644 --- a/Maths/AbsoluteMax.java +++ b/Maths/AbsoluteMax.java @@ -15,7 +15,7 @@ public static void main(String[] args) { } /** - * get the value, it's absolute value is max + * get the value, return the absolute max value * * @param numbers contains elements * @return the absolute max value diff --git a/Maths/AbsoluteMin.java b/Maths/AbsoluteMin.java index 4af43c5c08ac..576019581f9c 100644 --- a/Maths/AbsoluteMin.java +++ b/Maths/AbsoluteMin.java @@ -15,7 +15,7 @@ public static void main(String[] args) { } /** - * get the value, it's absolute value is min + * get the value, returns the absolute min value min * * @param numbers contains elements * @return the absolute min value diff --git a/Maths/Factorial.java b/Maths/Factorial.java index 1734e93fb83d..3feb43356129 100644 --- a/Maths/Factorial.java +++ b/Maths/Factorial.java @@ -1,25 +1,28 @@ package Maths; +//change around 'n' for different factorial results public class Factorial { public static void main(String[] args) { int n = 5; System.out.println(n + "! = " + factorial(n)); } + //Factorial = n! = n1 * (n-1) * (n-2)*...1 + /** - * Calculate factorial + * Calculate factorial N * * @param n the number * @return the factorial of {@code n} */ public static long factorial(int n) { if (n < 0) { - throw new ArithmeticException("n < 0"); + throw new ArithmeticException("n < 0"); //Dont work with less than 0 } long fac = 1; for (int i = 1; i <= n; ++i) { fac *= i; } - return fac; + return fac; //Return factorial } } diff --git a/Maths/Pow.java b/Maths/Pow.java index 605e01d98234..ac58fbbbe7cd 100644 --- a/Maths/Pow.java +++ b/Maths/Pow.java @@ -1,11 +1,12 @@ -package maths; +package Maths; +//POWER (exponentials) Examples (a^b) public class Pow { public static void main(String[] args) { - assert pow(2, 0) == Math.pow(2, 0); - assert pow(0, 2) == Math.pow(0, 2); - assert pow(2, 10) == Math.pow(2, 10); - assert pow(10, 2) == Math.pow(10, 2); + assert pow(2, 0) == Math.pow(2, 0); // == 1 + assert pow(0, 2) == Math.pow(0, 2); // == 0 + assert pow(2, 10) == Math.pow(2, 10); // == 1024 + assert pow(10, 2) == Math.pow(10, 2); // == 100 } /** diff --git a/Maths/PrimeCheck.java b/Maths/PrimeCheck.java index 3093894a3a3f..c972aa8c3e5a 100644 --- a/Maths/PrimeCheck.java +++ b/Maths/PrimeCheck.java @@ -13,6 +13,7 @@ public static void main(String[] args) { } else { System.out.println(n + " is not a prime number"); } + scanner.close(); } /*** diff --git a/MinimizingLateness/MinimizingLateness.java b/MinimizingLateness/MinimizingLateness.java index e5f71e9ef44a..1438f6f3dbcc 100644 --- a/MinimizingLateness/MinimizingLateness.java +++ b/MinimizingLateness/MinimizingLateness.java @@ -53,5 +53,6 @@ public static void main(String[] args) throws IOException { System.out.println(); System.out.println("Output Data : "); System.out.println(lateness); + in.close(); } } diff --git a/Misc/PalindromePrime.java b/Misc/PalindromePrime.java index b13a23d83792..77a918c32297 100644 --- a/Misc/PalindromePrime.java +++ b/Misc/PalindromePrime.java @@ -9,6 +9,7 @@ public static void main(String[] args) { // Main funtion System.out.println("Enter the quantity of First Palindromic Primes you want"); int n = in.nextInt(); // Input of how many first pallindromic prime we want functioning(n); // calling function - functioning + in.close(); } public static boolean prime(int num) { // checking if number is prime or not diff --git a/Others/BestFit.java b/Others/BestFit.java new file mode 100644 index 000000000000..71814d22b9f1 --- /dev/null +++ b/Others/BestFit.java @@ -0,0 +1,89 @@ +package Others; + +import java.util.ArrayList; + +/** + * @author Dekas Dimitrios + */ +public class BestFit { + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. + + /** + * Method to find the maximum valued element of an array filled with positive integers. + * + * @param array: an array filled with positive integers. + * @return the maximum valued element of the array. + */ + private static int findMaxElement(int[] array) { + int max = -1; + for (int value : array) { + if (value > max) { + max = value; + } + } + return max; + } + + /** + * Method to find the index of the memory block that is going to fit the given process based on the best fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findBestFit(int[] blockSizes, int processSize) { + // Initialize minDiff with an unreachable value by a difference between a blockSize and the processSize. + int minDiff = findMaxElement(blockSizes); + int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the result. + for(int i=0 ; i < blockSizes.length ; i++) { // Find the most fitting memory block for the given process. + if(blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { + minDiff = blockSizes[i] - processSize; + index = i; + } + } + return index; + } + + /** + * Method to allocate memory to blocks according to the best fit + * algorithm. It should return an ArrayList of Integers, where the + * index is the process ID (zero-indexed) and the value is the block + * number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the best-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for(int processSize : sizeOfProcesses) { + int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } + } + return memAlloc; + } + + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the bestFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) + System.out.print(memAllocation.get(i)); + else + System.out.print("Not Allocated"); + System.out.println(); + } + } +} \ No newline at end of file diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java deleted file mode 100644 index c2b1558e88db..000000000000 --- a/Others/Dijkshtra.java +++ /dev/null @@ -1,84 +0,0 @@ -package Others; - -import java.util.Arrays; -import java.util.Scanner; -import java.util.Stack; - -/** - * @author Mayank K Jha - */ - -public class Dijkshtra { - - public static void main(String[] args) { - Scanner in = new Scanner(System.in); - - // n = Number of nodes or vertices - int n = in.nextInt(); - // m = Number of Edges - int m = in.nextInt(); - - // Adjacency Matrix - long[][] w = new long[n + 1][n + 1]; - - // Initializing Matrix with Certain Maximum Value for path b/w any two vertices - for (long[] row : w) { - Arrays.fill(row, 1000000L); - } - - /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l - For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */ - - // Taking Input as Edge Location b/w a pair of vertices - for (int i = 0; i < m; i++) { - int x = in.nextInt(), y = in.nextInt(); - long cmp = in.nextLong(); - - // Comparing previous edge value with current value - Cycle Case - if (w[x][y] > cmp) { - w[x][y] = cmp; - w[y][x] = cmp; - } - } - - // Implementing Dijkshtra's Algorithm - Stack t = new Stack<>(); - int src = in.nextInt(); - - for (int i = 1; i <= n; i++) { - if (i != src) { - t.push(i); - } - } - - Stack p = new Stack<>(); - p.push(src); - w[src][src] = 0; - - while (!t.isEmpty()) { - int min = 989997979; - int loc = -1; - - for (int i = 0; i < t.size(); i++) { - w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]); - if (w[src][t.elementAt(i)] <= min) { - min = (int) w[src][t.elementAt(i)]; - loc = i; - } - } - p.push(t.elementAt(loc)); - t.removeElementAt(loc); - } - - // Printing shortest path from the given source src - for (int i = 1; i <= n; i++) { - if (i != src && w[src][i] != 1000000L) { - System.out.print(w[src][i] + " "); - } - // Printing -1 if there is no path b/w given pair of edges - else if (i != src) { - System.out.print("-1" + " "); - } - } - } -} \ No newline at end of file diff --git a/Others/FirstFit.java b/Others/FirstFit.java new file mode 100644 index 000000000000..61a25b422017 --- /dev/null +++ b/Others/FirstFit.java @@ -0,0 +1,70 @@ +package Others; + +import java.util.ArrayList; + +/** + * @author Dekas Dimitrios + */ +public class FirstFit { + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. + + /** + * Method to find the index of the memory block that is going to fit the given process based on the first fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findFirstFit(int[] blockSizes, int processSize) { + for(int i=0 ; i < blockSizes.length ; i++) { + if(blockSizes[i] >= processSize) { + return i; + } + } + // If there is not a block that can fit the process, return -255 as the result + return NO_ALLOCATION; + } + + /** + * Method to allocate memory to blocks according to the first fit + * algorithm. It should return an ArrayList of Integers, where the + * index is the process ID (zero-indexed) and the value is the block + * number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the first-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for(int processSize : sizeOfProcesses) { + int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } + } + return memAlloc; + } + + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the firstFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) + System.out.print(memAllocation.get(i)); + else + System.out.print("Not Allocated"); + System.out.println(); + } + } +} \ No newline at end of file diff --git a/Others/InsertDeleteInArray.java b/Others/InsertDeleteInArray.java index 40fd43b2e769..dfb702847275 100644 --- a/Others/InsertDeleteInArray.java +++ b/Others/InsertDeleteInArray.java @@ -44,5 +44,6 @@ public static void main(String[] args) { } for (i = 0; i < size2 - 1; i++) System.out.println(b[i]); + s.close(); } } diff --git a/Others/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java index 97b445b2ff61..2f8831100d3d 100644 --- a/Others/LowestBasePalindrome.java +++ b/Others/LowestBasePalindrome.java @@ -29,6 +29,7 @@ public static void main(String[] args) { } System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n)); System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n))); + in.close(); } /** diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java index dbd0a86e4512..f0e7f63dae31 100644 --- a/Others/PerlinNoise.java +++ b/Others/PerlinNoise.java @@ -162,5 +162,6 @@ public static void main(String[] args) { System.out.println(); } + in.close(); } } diff --git a/Others/PowerOfTwoOrNot.java b/Others/PowerOfTwoOrNot.java index 349eb9de5807..8f0400133066 100644 --- a/Others/PowerOfTwoOrNot.java +++ b/Others/PowerOfTwoOrNot.java @@ -20,6 +20,7 @@ public static void main(String[] args) { } else { System.out.println("Number is not a power of two"); } + sc.close(); } @@ -32,5 +33,4 @@ public static void main(String[] args) { public static boolean checkIfPowerOfTwoOrNot(int number) { return number != 0 && ((number & (number - 1)) == 0); } - } diff --git a/Others/ReturnSubsequence.java b/Others/ReturnSubsequence.java index bb1b413afd1d..89e945f8261e 100644 --- a/Others/ReturnSubsequence.java +++ b/Others/ReturnSubsequence.java @@ -13,6 +13,7 @@ public static void main(String[] args) { for (int i = 0; i < subsequence.length; i++) { System.out.println(subsequence[i]); } + s.close(); } /** diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java index 388f1b2ec7b6..71690a4b2591 100644 --- a/Others/RootPrecision.java +++ b/Others/RootPrecision.java @@ -14,6 +14,8 @@ public static void main(String[] args) { // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. int P = scn.nextInt(); System.out.println(squareRoot(N, P)); + + scn.close(); } public static double squareRoot(int N, int P) { diff --git a/Others/SJF.java b/Others/SJF.java index e6b995f4846c..247f3da0989f 100644 --- a/Others/SJF.java +++ b/Others/SJF.java @@ -67,6 +67,7 @@ class Schedule { processes.add(p); burstAll += p.burstTime; } + in.close(); } diff --git a/Others/StackPostfixNotation.java b/Others/StackPostfixNotation.java index 01e4c8a8eb1c..2857199d0401 100644 --- a/Others/StackPostfixNotation.java +++ b/Others/StackPostfixNotation.java @@ -7,6 +7,7 @@ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" System.out.println(postfixEvaluate(post)); + scanner.close(); } // Evaluates the given postfix expression string and returns the result. @@ -35,6 +36,7 @@ public static int postfixEvaluate(String exp) { // "+", "-", "*", "/" } } + tokens.close(); return s.pop(); } } diff --git a/Others/TopKWords.java b/Others/TopKWords.java index 840c3c2f7010..6cccfc27b95f 100644 --- a/Others/TopKWords.java +++ b/Others/TopKWords.java @@ -82,6 +82,7 @@ public static void main(String[] args) { for (int i = 0; i < k; i++) { System.out.println(list.get(list.size() - i - 1)); } + input.close(); } } diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java index 2eca7fc744a0..7d35ed36d54f 100644 --- a/Others/TowerOfHanoi.java +++ b/Others/TowerOfHanoi.java @@ -22,5 +22,6 @@ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1 shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called + scanner.close(); } } diff --git a/Others/WorstFit.java b/Others/WorstFit.java new file mode 100644 index 000000000000..0bb6c460b6b9 --- /dev/null +++ b/Others/WorstFit.java @@ -0,0 +1,76 @@ +package Others; + +import java.util.ArrayList; + +/** + * @author Dekas Dimitrios + */ +public class WorstFit { + private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255, + // it means that it has not been actually allocated. + + /** + * Method to find the index of the memory block that is going to fit the given process based on the worst fit algorithm. + * + * @param blocks: the array with the available memory blocks. + * @param process: the size of the process. + * @return the index of the block that fits, or -255 if no such block exists. + */ + private static int findWorstFit(int[] blockSizes, int processSize) { + int max = -1; + int index = -1; + for(int i=0 ; i < blockSizes.length ; i++) { // Find the index of the biggest memory block available. + if(blockSizes[i] > max) { + max = blockSizes[i]; + index = i; + } + } + // If the biggest memory block cannot fit the process, return -255 as the result + if(processSize > blockSizes[index]) { + return NO_ALLOCATION; + } + return index; + } + + /** + * Method to allocate memory to blocks according to the worst fit + * algorithm. It should return an ArrayList of Integers, where the + * index is the process ID (zero-indexed) and the value is the block + * number (also zero-indexed). + * + * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available. + * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for. + * @return the ArrayList filled with Integers repressenting the memory allocation that took place. + */ + static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the worst-fit algorithm + ArrayList memAlloc = new ArrayList<>(); + // Do this for every process + for(int processSize : sizeOfProcesses) { + int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list + if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + } + } + return memAlloc; + } + + /** + * Method to print the memory allocated. + * + * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the worstFit method. + */ + public static void printMemoryAllocation(ArrayList memAllocation) { + System.out.println("Process No.\tBlock No."); + System.out.println("===========\t========="); + for (int i = 0; i < memAllocation.size(); i++) { + System.out.print(" " + i + "\t\t"); + if (memAllocation.get(i) != NO_ALLOCATION) + System.out.print(memAllocation.get(i)); + else + System.out.print("Not Allocated"); + System.out.println(); + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index d0dd123e4d4e..80b5888a5165 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,15 @@ [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100) -NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we are trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info. +NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we're trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info. -You can play around (run and edit) the Algorithms or contribute to them using Gitpod.io a free online dev environment with a single click. No need to worry about the Dev enviroment. +You can run and edit the algorithms or contribute to them using Gitpod.io, a free online development environment, with a single click. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) -### All algorithms implemented in Java (for education) -These implementations are for learning purposes. They may be less efficient than the implementations in the Java standard library. +### All algorithms are implemented in Java (for education purposes) +These implementations are for learning purposes. The implementations may be less efficient than the Java standard library. ## Contribution Guidelines Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. diff --git a/Sorts/BogoSort.java b/Sorts/BogoSort.java index 299c6b90ec5d..439d51ec6935 100644 --- a/Sorts/BogoSort.java +++ b/Sorts/BogoSort.java @@ -12,7 +12,7 @@ public class BogoSort implements SortAlgorithm { private static final Random random = new Random(); - private static > boolean isSorted(T array[]) { + private static > boolean isSorted(T[] array) { for (int i = 0; i < array.length - 1; i++) { if (SortUtils.less(array[i + 1], array[i])) return false; } @@ -20,7 +20,7 @@ private static > boolean isSorted(T array[]) { } // Randomly shuffles the array - private static void nextPermutation(T array[]) { + private static void nextPermutation(T[] array) { int length = array.length; for (int i = 0; i < array.length; i++) { @@ -29,7 +29,7 @@ private static void nextPermutation(T array[]) { } } - public > T[] sort(T array[]) { + public > T[] sort(T[] array) { while (!isSorted(array)) { nextPermutation(array); } diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java index 29d588932c8f..9d2f371786d8 100644 --- a/Sorts/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -17,11 +17,14 @@ class BubbleSort implements SortAlgorithm { **/ @Override - public > T[] sort(T array[]) { + public > T[] sort(T[] array) { for (int i = 0, size = array.length; i < size - 1; ++i) { boolean swapped = false; for (int j = 0; j < size - 1 - i; ++j) { - swapped = less(array[j], array[j + 1]) && swap(array, j, j + 1); + if (less(array[j], array[j + 1])) { + swap(array, j, j + 1); + swapped = true; + } } if (!swapped) { break; diff --git a/Sorts/CombSort.java b/Sorts/CombSort.java index 23e38323ef36..652fc9f945a6 100644 --- a/Sorts/CombSort.java +++ b/Sorts/CombSort.java @@ -33,7 +33,7 @@ private int nextGap(int gap) { * @return sorted array */ @Override - public > T[] sort(T arr[]) { + public > T[] sort(T[] arr) { int size = arr.length; // initialize gap @@ -62,9 +62,9 @@ public > T[] sort(T arr[]) { } // Driver method - public static void main(String args[]) { + public static void main(String[] args) { CombSort ob = new CombSort(); - Integer arr[] = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; + Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0}; ob.sort(arr); System.out.println("sorted array"); diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java index 90392293b58f..2b15a9ce09b4 100644 --- a/Sorts/MergeSort.java +++ b/Sorts/MergeSort.java @@ -22,24 +22,22 @@ class MergeSort implements SortAlgorithm { @Override @SuppressWarnings("unchecked") public > T[] sort(T[] unsorted) { - T[] tmp = (T[]) new Comparable[unsorted.length]; - doSort(unsorted, tmp, 0, unsorted.length - 1); + doSort(unsorted, 0, unsorted.length - 1); return unsorted; } /** * @param arr The array to be sorted - * @param temp The copy of the actual array * @param left The first index of the array * @param right The last index of the array * Recursively sorts the array in increasing order **/ - private static > void doSort(T[] arr, T[] temp, int left, int right) { + private static > void doSort(T[] arr, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; - doSort(arr, temp, left, mid); - doSort(arr, temp, mid + 1, right); - merge(arr, temp, left, mid, right); + doSort(arr, left, mid); + doSort(arr, mid + 1, right); + merge(arr, left, mid, right); } } @@ -48,36 +46,36 @@ private static > void doSort(T[] arr, T[] temp, int left * This method implements the merge step of the merge sort * * @param arr The array to be sorted - * @param temp The copy of the actual array * @param left The first index of the array * @param mid The middle index of the array * @param right The last index of the array * merges two parts of an array in increasing order **/ - private static > void merge(T[] arr, T[] temp, int left, int mid, int right) { - System.arraycopy(arr, left, temp, left, right - left + 1); - - + private static > void merge(T[] arr, int left, int mid, int right) { + int length = right - left + 1; + T[] temp = (T[]) new Comparable[length]; int i = left; int j = mid + 1; - int k = left; + int k = 0; while (i <= mid && j <= right) { - if (temp[i].compareTo(temp[j]) <= 0) { - arr[k++] = temp[i++]; + if (arr[i].compareTo(arr[j]) <= 0) { + temp[k++] = arr[i++]; } else { - arr[k++] = temp[j++]; + temp[k++] = arr[j++]; } } while (i <= mid) { - arr[k++] = temp[i++]; + temp[k++] = arr[i++]; } while (j <= right) { - arr[k++] = temp[j++]; + temp[k++] = arr[j++]; } + + System.arraycopy(temp, 0, arr, left, length); } // Driver program diff --git a/Sorts/RadixSort.java b/Sorts/RadixSort.java index a207f6bbdda3..ca9ed767eaa0 100644 --- a/Sorts/RadixSort.java +++ b/Sorts/RadixSort.java @@ -4,7 +4,7 @@ class RadixSort { - private static int getMax(int arr[], int n) { + private static int getMax(int[] arr, int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) @@ -12,10 +12,10 @@ private static int getMax(int arr[], int n) { return mx; } - private static void countSort(int arr[], int n, int exp) { - int output[] = new int[n]; + private static void countSort(int[] arr, int n, int exp) { + int[] output = new int[n]; int i; - int count[] = new int[10]; + int[] count = new int[10]; Arrays.fill(count, 0); for (i = 0; i < n; i++) @@ -33,7 +33,7 @@ private static void countSort(int arr[], int n, int exp) { arr[i] = output[i]; } - private static void radixsort(int arr[], int n) { + private static void radixsort(int[] arr, int n) { int m = getMax(arr, n); @@ -43,14 +43,14 @@ private static void radixsort(int arr[], int n) { } - static void print(int arr[], int n) { + static void print(int[] arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } public static void main(String[] args) { - int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; + int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; int n = arr.length; radixsort(arr, n); print(arr, n); diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java index 49be29b9d200..199f31a8c1ea 100644 --- a/Sorts/ShellSort.java +++ b/Sorts/ShellSort.java @@ -2,48 +2,40 @@ import static Sorts.SortUtils.*; - -/** - * @author dpunosevac - * @author Podshivalov Nikita (https://github.com/nikitap492) - * @see SortAlgorithm - */ public class ShellSort implements SortAlgorithm { /** * This method implements Generic Shell Sort. * - * @param array The array to be sorted + * @param array the array to be sorted */ @Override public > T[] sort(T[] array) { - int N = array.length; - int h = 1; + int length = array.length; + int gap = 1; - while (h < N / 3) { - h = 3 * h + 1; + /* Calculate gap for optimization purpose */ + while (gap < length / 3) { + gap = 3 * gap + 1; } - while (h >= 1) { - for (int i = h; i < N; i++) { - for (int j = i; j >= h && less(array[j], array[j - h]); j -= h) { - swap(array, j, j - h); + for (; gap > 0; gap /= 3) { + for (int i = gap; i < length; i++) { + int j; + for (j = i; j >= gap && less(array[j], array[j - gap]); j -= gap) { + array[j] = array[j - gap]; } + array[j] = array[i]; } - - h /= 3; } - return array; } + /* Driver Code */ public static void main(String[] args) { Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; ShellSort sort = new ShellSort(); - Integer[] sorted = sort.sort(toSort); - - print(sorted); - + print(sort.sort(toSort)); } } diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java index 06319f79df49..cec0ddce0065 100644 --- a/ciphers/Caesar.java +++ b/ciphers/Caesar.java @@ -126,6 +126,7 @@ public static void main(String[] args) { case 'd': System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); } + input.close(); } } diff --git a/ciphers/SimpleSubstitutionCipher.java b/ciphers/SimpleSubstitutionCipher.java new file mode 100644 index 000000000000..d9bae4f072c8 --- /dev/null +++ b/ciphers/SimpleSubstitutionCipher.java @@ -0,0 +1,97 @@ +package ciphers; + +import java.util.*; + +/** + * + * The simple substitution cipher is a cipher that has been in use for many hundreds of years + * (an excellent history is given in Simon Singhs 'the Code Book'). + * It basically consists of substituting every plaintext character for a different ciphertext character. + * It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted, + * it is completely jumbled. + * + * @author Hassan Elseoudy + */ + +public class SimpleSubstitutionCipher { + + /** + * Encrypt text by replacing each element with its opposite character. + * + * @param message + * @param cipherSmall + * @return Encrypted message + */ + public static String encode(String message, String cipherSmall) { + String encoded = ""; + + // This map is used to encode + Map cipherMap = new HashMap(); + + char beginSmallLetter = 'a'; + char beginCapitalLetter = 'A'; + + cipherSmall = cipherSmall.toLowerCase(); + String cipherCapital = cipherSmall.toUpperCase(); + + // To handle Small and Capital letters + for(int i = 0; i < cipherSmall.length(); i++){ + cipherMap.put(beginSmallLetter++,cipherSmall.charAt(i)); + cipherMap.put(beginCapitalLetter++,cipherCapital.charAt(i)); + } + + for(int i = 0; i < message.length(); i++){ + if(Character.isAlphabetic(message.charAt(i))) + encoded += cipherMap.get(message.charAt(i)); + else + encoded += message.charAt(i); + } + + return encoded; + } + + /** + * Decrypt message by replacing each element with its opposite character in cipher. + * + * @param encryptedMessage + * @param cipherSmall + * @return message + */ + public static String decode(String encryptedMessage, String cipherSmall) { + String decoded = ""; + + + Map cipherMap = new HashMap(); + + char beginSmallLetter = 'a'; + char beginCapitalLetter = 'A'; + + cipherSmall = cipherSmall.toLowerCase(); + String cipherCapital = cipherSmall.toUpperCase(); + + for(int i = 0; i < cipherSmall.length(); i++){ + cipherMap.put(cipherSmall.charAt(i),beginSmallLetter++); + cipherMap.put(cipherCapital.charAt(i),beginCapitalLetter++); + } + + for(int i = 0; i < encryptedMessage.length(); i++){ + if(Character.isAlphabetic(encryptedMessage.charAt(i))) + decoded += cipherMap.get(encryptedMessage.charAt(i)); + else + decoded += encryptedMessage.charAt(i); + } + + return decoded; + } + + /** + * + * TODO remove main and make JUnit Testing + */ + public static void main(String[] args) { + String a = encode("defend the east wall of the castle","phqgiumeaylnofdxjkrcvstzwb"); + String b = decode(a,"phqgiumeaylnofdxjkrcvstzwb"); + System.out.println(b); + } + +}