From dfe189b21f7403489aa17d540b47ecc736fdff10 Mon Sep 17 00:00:00 2001 From: Andrii Siriak Date: Sun, 26 Sep 2021 12:26:59 +0300 Subject: [PATCH] Resolve build errors & cleanup structure (#2334) --- .github/ISSUE_TEMPLATE/bug_report.md | 8 +- .github/ISSUE_TEMPLATE/feature_request.md | 7 +- .github/workflows/build.yml | 14 +- .github/workflows/checkstyle.yml | 29 -- .../workflows/{prettier.yml => prettify.yml} | 16 +- .github/workflows/stale.yml | 3 +- ..._directory_md.yml => update_directory.yml} | 8 +- .travis.yml | 10 - CONTRIBUTING.md | 2 - {ciphers => Ciphers}/AES.java | 69 ++-- {ciphers => Ciphers}/AESEncryption.java | 21 +- {ciphers => Ciphers}/Caesar.java | 28 +- .../ColumnarTranspositionCipher.java | 43 +-- {ciphers => Ciphers}/RSA.java | 9 +- .../SimpleSubstitutionCipher.java | 26 +- {ciphers => Ciphers}/Vigenere.java | 124 +++---- Code.html | 68 ---- DIRECTORY.md | 58 ++- DataStructures/Graphs/A_Star.java | 35 +- .../HashMap/Hashing/HashMapLinearProbing.java | 8 +- DataStructures/Stacks/README.md | 9 +- DataStructures/Trees/AVLSimple | 2 +- .../ClosestPair.java | 28 +- .../SkylineAlgorithm.java | 338 +++++++++--------- ProjectEuler/Problem01.java | 51 --- ProjectEuler/Problem02.java | 43 --- ProjectEuler/Problem03.java | 62 ---- ProjectEuler/Problem04.java | 41 --- ProjectEuler/Problem06.java | 42 --- ProjectEuler/Problem07.java | 60 ---- ProjectEuler/Problem09.java | 28 -- ProjectEuler/Problem10.java | 55 --- ProjectEuler/Problem12.java | 54 --- README-ko.md | 42 +-- README.md | 10 +- REVIEWER.md | 13 - Searches/IBSearch_test.java | 32 -- {strings => Strings}/Alphabetical.java | 2 +- {strings => Strings}/CharactersSame.java | 2 +- {strings => Strings}/CheckAnagrams.java | 2 +- {strings => Strings}/CheckVowels.java | 4 +- {strings => Strings}/HorspoolSearch.java | 2 +- {strings => Strings}/Lower.java | 2 +- {strings => Strings}/Palindrome.java | 2 +- {strings => Strings}/Pangram.java | 2 +- {strings => Strings}/ReverseString.java | 2 +- {strings => Strings}/Rotation.java | 2 +- {strings => Strings}/Upper.java | 2 +- 48 files changed, 418 insertions(+), 1102 deletions(-) delete mode 100644 .github/workflows/checkstyle.yml rename .github/workflows/{prettier.yml => prettify.yml} (61%) rename .github/workflows/{update_directory_md.yml => update_directory.yml} (95%) delete mode 100644 .travis.yml rename {ciphers => Ciphers}/AES.java (95%) rename {ciphers => Ciphers}/AESEncryption.java (85%) rename {ciphers => Ciphers}/Caesar.java (80%) rename {ciphers => Ciphers}/ColumnarTranspositionCipher.java (89%) rename {ciphers => Ciphers}/RSA.java (92%) rename {ciphers => Ciphers}/SimpleSubstitutionCipher.java (77%) rename {ciphers => Ciphers}/Vigenere.java (95%) delete mode 100644 Code.html rename {divideconquer => DivideAndConquer}/ClosestPair.java (95%) rename {divideconquer => DivideAndConquer}/SkylineAlgorithm.java (96%) delete mode 100644 ProjectEuler/Problem01.java delete mode 100644 ProjectEuler/Problem02.java delete mode 100644 ProjectEuler/Problem03.java delete mode 100644 ProjectEuler/Problem04.java delete mode 100644 ProjectEuler/Problem06.java delete mode 100644 ProjectEuler/Problem07.java delete mode 100644 ProjectEuler/Problem09.java delete mode 100644 ProjectEuler/Problem10.java delete mode 100644 ProjectEuler/Problem12.java delete mode 100644 REVIEWER.md delete mode 100644 Searches/IBSearch_test.java rename {strings => Strings}/Alphabetical.java (98%) rename {strings => Strings}/CharactersSame.java (97%) rename {strings => Strings}/CheckAnagrams.java (98%) rename {strings => Strings}/CheckVowels.java (96%) rename {strings => Strings}/HorspoolSearch.java (99%) rename {strings => Strings}/Lower.java (97%) rename {strings => Strings}/Palindrome.java (99%) rename {strings => Strings}/Pangram.java (98%) rename {strings => Strings}/ReverseString.java (98%) rename {strings => Strings}/Rotation.java (98%) rename {strings => Strings}/Upper.java (97%) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index e63d7f94..ba390faf 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,10 +1,9 @@ --- name: Bug report about: Create a report to help us improve -title: '' -labels: '' -assignees: '' - +title: "" +labels: "" +assignees: "" --- **Describe the bug** @@ -12,6 +11,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index bbcbbe7d..2bc5d5f7 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,10 +1,9 @@ --- name: Feature request about: Suggest an idea for this project -title: '' -labels: '' -assignees: '' - +title: "" +labels: "" +assignees: "" --- **Is your feature request related to a problem? Please describe.** diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0ef61267..8376551a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,20 +1,14 @@ -name: Build Project - -on: - pull_request: - push: - branches: - - master - +name: Build +on: push jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - - name: Set up JDK 12 + - name: Set up JDK 17 uses: actions/setup-java@v1 with: - java-version: 12 + java-version: 17 - run: find . -type f -name "*.java" > sources.txt - run: javac @sources.txt \ No newline at end of file diff --git a/.github/workflows/checkstyle.yml b/.github/workflows/checkstyle.yml deleted file mode 100644 index 9845df46..00000000 --- a/.github/workflows/checkstyle.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: Code Formatter - -on: - push: - branches: [master, Development] - paths: - - "**.java" - -jobs: - format: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@master - - - name: Set up JDK 12 - uses: actions/setup-java@v1 - with: - java-version: 12 - - run: wget https://github.com/google/google-java-format/releases/download/google-java-format-1.9/google-java-format-1.9-all-deps.jar -O formatter.jar - - run: java -jar formatter.jar --replace --set-exit-if-changed $(find . -type f -name "*.java") - - name: Commit Format changes - if: failure() - run: | - git diff - 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 commit -am "Formatted with Google Java Formatter" || true - git push --force origin HEAD:$GITHUB_REF || true diff --git a/.github/workflows/prettier.yml b/.github/workflows/prettify.yml similarity index 61% rename from .github/workflows/prettier.yml rename to .github/workflows/prettify.yml index 35595927..0d2e0647 100644 --- a/.github/workflows/prettier.yml +++ b/.github/workflows/prettify.yml @@ -1,16 +1,8 @@ -name: Prettier - -on: - pull_request: - push: - branches: - - master - - Development - +name: Prettify +on: push jobs: prettier: runs-on: ubuntu-latest - steps: - name: Checkout uses: actions/checkout@v2 @@ -20,7 +12,7 @@ jobs: - name: Prettify code uses: creyD/prettier_action@v3.3 with: - prettier_options: --write **/*.{java} - commit_message: 'style: prettify code' + prettier_options: --write **/*.java + commit_message: 'Prettify code' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index c74db830..8fbb262b 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,7 +1,7 @@ name: 'Close stale issues and PRs' on: schedule: - - cron: '0 */10 * * *' + - cron: '0 0 * * *' jobs: stale: runs-on: ubuntu-latest @@ -16,4 +16,3 @@ jobs: exempt-pr-labels: 'dont-close' days-before-stale: 30 days-before-close: 7 - operations-per-run: 150 diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory.yml similarity index 95% rename from .github/workflows/update_directory_md.yml rename to .github/workflows/update_directory.yml index 325fa045..4d5af6bc 100644 --- a/.github/workflows/update_directory_md.yml +++ b/.github/workflows/update_directory.yml @@ -1,13 +1,13 @@ # This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push -name: update_directory_md -on: [push] +name: Update Directory +on: push jobs: update_directory_md: runs-on: ubuntu-latest steps: - uses: actions/checkout@master - uses: actions/setup-python@master - - name: update_directory_md + - name: Update Directory shell: python run: | import os @@ -63,5 +63,5 @@ jobs: 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 commit -am "Update directory" || true git push --force origin HEAD:$GITHUB_REF || true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 641567ba..00000000 --- a/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -os: linux -dist: focal -language: java -script: - - find . -type f -name "*.java" > sources.txt - - javac -Xlint:deprecation -Xlint:unchecked @sources.txt -notifications: - webhooks: https://www.travisbuddy.com/ - on_success: never - on_failure: always diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d9681c07..c15c0c3b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,3 @@ -:+1::tada: Before guiding you through the contribution process TheAlgorithms/Java thank you for being one of us! :+1::tada: - ## How to contribute? #### **Did you find a bug?** diff --git a/ciphers/AES.java b/Ciphers/AES.java similarity index 95% rename from ciphers/AES.java rename to Ciphers/AES.java index 433ae15b..d5211d3b 100644 --- a/ciphers/AES.java +++ b/Ciphers/AES.java @@ -1,4 +1,4 @@ -package ciphers; +package Ciphers; import java.math.BigInteger; import java.util.Scanner; @@ -215,30 +215,26 @@ public class AES { /** * Subroutine of the Rijndael key expansion. - * - * @param t - * @param rconCounter - * @return */ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { - String rBytes = t.toString(16); + StringBuilder rBytes = new StringBuilder(t.toString(16)); // Add zero padding while (rBytes.length() < 8) { - rBytes = "0" + rBytes; + rBytes.insert(0, "0"); } // rotate the first 16 bits to the back String rotatingBytes = rBytes.substring(0, 2); String fixedBytes = rBytes.substring(2); - rBytes = fixedBytes + rotatingBytes; + rBytes = new StringBuilder(fixedBytes + rotatingBytes); // apply S-Box to all 8-Bit Substrings for (int i = 0; i < 4; i++) { - String currentByteBits = rBytes.substring(i * 2, (i + 1) * 2); + StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2)); - int currentByte = Integer.parseInt(currentByteBits, 16); + int currentByte = Integer.parseInt(currentByteBits.toString(), 16); currentByte = SBOX[currentByte]; // add the current RCON value to the first byte @@ -246,27 +242,26 @@ public class AES { currentByte = currentByte ^ RCON[rconCounter]; } - currentByteBits = Integer.toHexString(currentByte); + currentByteBits = new StringBuilder(Integer.toHexString(currentByte)); // Add zero padding while (currentByteBits.length() < 2) { - currentByteBits = '0' + currentByteBits; + currentByteBits.insert(0, '0'); } // replace bytes in original string - rBytes = rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2); + rBytes = new StringBuilder(rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2)); } // t = new BigInteger(rBytes, 16); // return t; - return new BigInteger(rBytes, 16); + return new BigInteger(rBytes.toString(), 16); } /** * Returns an array of 10 + 1 round keys that are calculated by using Rijndael key schedule * - * @param initialKey * @return array of 10 + 1 round keys */ public static BigInteger[] keyExpansion(BigInteger initialKey) { @@ -332,11 +327,11 @@ public class AES { public static int[] splitBlockIntoCells(BigInteger block) { int[] cells = new int[16]; - String blockBits = block.toString(2); + StringBuilder blockBits = new StringBuilder(block.toString(2)); // Append leading 0 for full "128-bit" string while (blockBits.length() < 128) { - blockBits = '0' + blockBits; + blockBits.insert(0, '0'); } // split 128 to 8 bit cells @@ -356,24 +351,22 @@ public class AES { */ public static BigInteger mergeCellsIntoBlock(int[] cells) { - String blockBits = ""; + StringBuilder blockBits = new StringBuilder(); for (int i = 0; i < 16; i++) { - String cellBits = Integer.toBinaryString(cells[i]); + StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i])); // Append leading 0 for full "8-bit" strings while (cellBits.length() < 8) { - cellBits = '0' + cellBits; + cellBits.insert(0, '0'); } - blockBits += cellBits; + blockBits.append(cellBits); } - return new BigInteger(blockBits, 2); + return new BigInteger(blockBits.toString(), 2); } /** - * @param ciphertext - * @param key * @return ciphertext XOR key */ public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { @@ -383,7 +376,6 @@ public class AES { /** * substitutes 8-Bit long substrings of the input using the S-Box and returns the result. * - * @param ciphertext * @return subtraction Output */ public static BigInteger subBytes(BigInteger ciphertext) { @@ -401,7 +393,6 @@ public class AES { * substitutes 8-Bit long substrings of the input using the inverse S-Box for decryption and * returns the result. * - * @param ciphertext * @return subtraction Output */ public static BigInteger subBytesDec(BigInteger ciphertext) { @@ -417,8 +408,6 @@ public class AES { /** * Cell permutation step. Shifts cells within the rows of the input and returns the result. - * - * @param ciphertext */ public static BigInteger shiftRows(BigInteger ciphertext) { int[] cells = splitBlockIntoCells(ciphertext); @@ -454,8 +443,6 @@ public class AES { /** * Cell permutation step for decryption . Shifts cells within the rows of the input and returns * the result. - * - * @param ciphertext */ public static BigInteger shiftRowsDec(BigInteger ciphertext) { int[] cells = splitBlockIntoCells(ciphertext); @@ -490,8 +477,6 @@ public class AES { /** * Applies the Rijndael MixColumns to the input and returns the result. - * - * @param ciphertext */ public static BigInteger mixColumns(BigInteger ciphertext) { @@ -511,8 +496,6 @@ public class AES { /** * Applies the inverse Rijndael MixColumns for decryption to the input and returns the result. - * - * @param ciphertext */ public static BigInteger mixColumnsDec(BigInteger ciphertext) { @@ -563,7 +546,6 @@ public class AES { * Decrypts the ciphertext with the key and returns the result * * @param cipherText The Encrypted text which we want to decrypt - * @param key * @return decryptedText */ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { @@ -596,8 +578,7 @@ public class AES { char choice = input.nextLine().charAt(0); String in; switch (choice) { - case 'E': - case 'e': + case 'E', 'e' -> { System.out.println("Choose a plaintext block (128-Bit Integer in base 16):"); in = input.nextLine(); BigInteger plaintext = new BigInteger(in, 16); @@ -605,10 +586,9 @@ public class AES { in = input.nextLine(); BigInteger encryptionKey = new BigInteger(in, 16); System.out.println( - "The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); - break; - case 'D': - case 'd': + "The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); + } + case 'D', 'd' -> { System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):"); in = input.nextLine(); BigInteger ciphertext = new BigInteger(in, 16); @@ -616,10 +596,9 @@ public class AES { in = input.nextLine(); BigInteger decryptionKey = new BigInteger(in, 16); System.out.println( - "The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); - break; - default: - System.out.println("** End **"); + "The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); + } + default -> System.out.println("** End **"); } } } diff --git a/ciphers/AESEncryption.java b/Ciphers/AESEncryption.java similarity index 85% rename from ciphers/AESEncryption.java rename to Ciphers/AESEncryption.java index 12e5824d..142aefdd 100644 --- a/ciphers/AESEncryption.java +++ b/Ciphers/AESEncryption.java @@ -1,4 +1,4 @@ -package ciphers; +package Ciphers; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -42,15 +42,12 @@ public class AESEncryption { public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); aesKeyGenerator.init(128); // The AES key size in number of bits - SecretKey secKey = aesKeyGenerator.generateKey(); - return secKey; + return aesKeyGenerator.generateKey(); } /** * Encrypts plainText in AES using the secret key * - * @param plainText - * @param secKey * @return byteCipherText (The encrypted text) * @throws NoSuchPaddingException (from Cipher) * @throws NoSuchAlgorithmException (from Cipher) @@ -64,21 +61,13 @@ public class AESEncryption { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); - byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes()); - return byteCipherText; + return aesCipher.doFinal(plainText.getBytes()); } /** * Decrypts encrypted byte array using the key used for encryption. * - * @param byteCipherText - * @param secKey * @return plainText - * @throws NoSuchPaddingException - * @throws NoSuchAlgorithmException - * @throws InvalidKeyException - * @throws BadPaddingException - * @throws IllegalBlockSizeException */ public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, @@ -92,10 +81,8 @@ public class AESEncryption { /** * Convert a binary byte array into readable hex form Old library is deprecated on OpenJdk 11 and - * this is faster regarding other solution is using StringBuilder Credit {@link - * https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338} + * this is faster regarding other solution is using StringBuilder * - * @param hash (in binary) * @return hexHash */ public static String bytesToHex(byte[] bytes) { diff --git a/ciphers/Caesar.java b/Ciphers/Caesar.java similarity index 80% rename from ciphers/Caesar.java rename to Ciphers/Caesar.java index ff7f4482..8bd38844 100644 --- a/ciphers/Caesar.java +++ b/Ciphers/Caesar.java @@ -1,4 +1,4 @@ -package ciphers; +package Ciphers; import java.util.Scanner; @@ -14,12 +14,10 @@ public class Caesar { /** * Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B * - * @param message - * @param shift * @return Encrypted message */ public static String encode(String message, int shift) { - String encoded = ""; + StringBuilder encoded = new StringBuilder(); shift %= 26; @@ -33,29 +31,27 @@ public class Caesar { if (IsCapitalLatinLetter(current)) { current += shift; - encoded += (char) (current > 'Z' ? current - 26 : current); // 26 = number of latin letters + encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters } else if (IsSmallLatinLetter(current)) { current += shift; - encoded += (char) (current > 'z' ? current - 26 : current); // 26 = number of latin letters + encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters } else { - encoded += current; + encoded.append(current); } } - return encoded; + return encoded.toString(); } /** * Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A * - * @param encryptedMessage - * @param shift * @return message */ public static String decode(String encryptedMessage, int shift) { - String decoded = ""; + StringBuilder decoded = new StringBuilder(); shift %= 26; @@ -65,22 +61,21 @@ public class Caesar { if (IsCapitalLatinLetter(current)) { current -= shift; - decoded += (char) (current < 'A' ? current + 26 : current); // 26 = number of latin letters + decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters } else if (IsSmallLatinLetter(current)) { current -= shift; - decoded += (char) (current < 'a' ? current + 26 : current); // 26 = number of latin letters + decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters } else { - decoded += current; + decoded.append(current); } } - return decoded; + return decoded.toString(); } /** - * @param c * @return true if character is capital Latin letter or false for others */ private static boolean IsCapitalLatinLetter(char c) { @@ -88,7 +83,6 @@ public class Caesar { } /** - * @param c * @return true if character is small Latin letter or false for others */ private static boolean IsSmallLatinLetter(char c) { diff --git a/ciphers/ColumnarTranspositionCipher.java b/Ciphers/ColumnarTranspositionCipher.java similarity index 89% rename from ciphers/ColumnarTranspositionCipher.java rename to Ciphers/ColumnarTranspositionCipher.java index 9947d781..272ebe92 100644 --- a/ciphers/ColumnarTranspositionCipher.java +++ b/Ciphers/ColumnarTranspositionCipher.java @@ -1,4 +1,6 @@ -package ciphers; +package Ciphers; + +import java.util.Objects; /** * Columnar Transposition Cipher Encryption and Decryption. @@ -27,13 +29,13 @@ public class ColumnarTranspositionCipher { abecedariumBuilder(500); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); - String wordEncrypted = ""; + StringBuilder wordEncrypted = new StringBuilder(); for (int i = 0; i < sortedTable[i].length; i++) { for (int j = 1; j < sortedTable.length; j++) { - wordEncrypted += sortedTable[j][i]; + wordEncrypted.append(sortedTable[j][i]); } } - return wordEncrypted; + return wordEncrypted.toString(); } /** @@ -46,20 +48,16 @@ public class ColumnarTranspositionCipher { */ public static String encrpyter(String word, String keyword, String abecedarium) { ColumnarTranspositionCipher.keyword = keyword; - if (abecedarium != null) { - ColumnarTranspositionCipher.abecedarium = abecedarium; - } else { - ColumnarTranspositionCipher.abecedarium = ABECEDARIUM; - } + ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); table = tableBuilder(word); Object[][] sortedTable = sortTable(table); - String wordEncrypted = ""; + StringBuilder wordEncrypted = new StringBuilder(); for (int i = 0; i < sortedTable[0].length; i++) { for (int j = 1; j < sortedTable.length; j++) { - wordEncrypted += sortedTable[j][i]; + wordEncrypted.append(sortedTable[j][i]); } } - return wordEncrypted; + return wordEncrypted.toString(); } /** @@ -68,13 +66,13 @@ public class ColumnarTranspositionCipher { * @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule */ public static String decrypter() { - String wordDecrypted = ""; + StringBuilder wordDecrypted = new StringBuilder(); for (int i = 1; i < table.length; i++) { for (Object item : table[i]) { - wordDecrypted += item; + wordDecrypted.append(item); } } - return wordDecrypted.replaceAll(ENCRYPTION_FIELD, ""); + return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, ""); } /** @@ -127,7 +125,6 @@ public class ColumnarTranspositionCipher { } /** - * @param table * @return tableSorted */ private static Object[][] sortTable(Object[][] table) { @@ -147,9 +144,6 @@ public class ColumnarTranspositionCipher { } /** - * @param table - * @param rows - * @param column * @return columnArray */ private static Object[] getColumn(Object[][] table, int rows, int column) { @@ -160,12 +154,6 @@ public class ColumnarTranspositionCipher { return columnArray; } - /** - * @param table - * @param firstColumnIndex - * @param secondColumnIndex - * @param columnToSwitch - */ private static void switchColumns( Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { for (int i = 0; i < table.length; i++) { @@ -180,10 +168,11 @@ public class ColumnarTranspositionCipher { * @param value Number of characters being used based on the ASCII Table */ private static void abecedariumBuilder(int value) { - abecedarium = ""; + StringBuilder t = new StringBuilder(); for (int i = 0; i < value; i++) { - abecedarium += (char) i; + t.append((char) i); } + abecedarium = t.toString(); } private static void showTable() { diff --git a/ciphers/RSA.java b/Ciphers/RSA.java similarity index 92% rename from ciphers/RSA.java rename to Ciphers/RSA.java index 0778f48c..43a940c4 100644 --- a/ciphers/RSA.java +++ b/Ciphers/RSA.java @@ -1,4 +1,4 @@ -package ciphers; +package Ciphers; import java.math.BigInteger; import java.security.SecureRandom; @@ -20,13 +20,11 @@ public final class RSA { private BigInteger modulus, privateKey, publicKey; - /** @param bits */ public RSA(int bits) { generateKeys(bits); } /** - * @param message * @return encrypted message */ public synchronized String encrypt(String message) { @@ -34,7 +32,6 @@ public final class RSA { } /** - * @param message * @return encrypted message as big integer */ public synchronized BigInteger encrypt(BigInteger message) { @@ -42,7 +39,6 @@ public final class RSA { } /** - * @param encryptedMessage * @return plain message */ public synchronized String decrypt(String encryptedMessage) { @@ -50,7 +46,6 @@ public final class RSA { } /** - * @param encryptedMessage * @return plain message as big integer */ public synchronized BigInteger decrypt(BigInteger encryptedMessage) { @@ -59,8 +54,6 @@ public final class RSA { /** * Generate a new public and private key set. - * - * @param bits */ public synchronized void generateKeys(int bits) { SecureRandom r = new SecureRandom(); diff --git a/ciphers/SimpleSubstitutionCipher.java b/Ciphers/SimpleSubstitutionCipher.java similarity index 77% rename from ciphers/SimpleSubstitutionCipher.java rename to Ciphers/SimpleSubstitutionCipher.java index 1279c494..2ac68554 100644 --- a/ciphers/SimpleSubstitutionCipher.java +++ b/Ciphers/SimpleSubstitutionCipher.java @@ -1,4 +1,4 @@ -package ciphers; +package Ciphers; import java.util.*; @@ -16,15 +16,13 @@ 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 = ""; + StringBuilder encoded = new StringBuilder(); // This map is used to encode - Map cipherMap = new HashMap(); + Map cipherMap = new HashMap<>(); char beginSmallLetter = 'a'; char beginCapitalLetter = 'A'; @@ -39,24 +37,22 @@ public class SimpleSubstitutionCipher { } 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); + if (Character.isAlphabetic(message.charAt(i))) encoded.append(cipherMap.get(message.charAt(i))); + else encoded.append(message.charAt(i)); } - return encoded; + return encoded.toString(); } /** * 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 = ""; + StringBuilder decoded = new StringBuilder(); - Map cipherMap = new HashMap(); + Map cipherMap = new HashMap<>(); char beginSmallLetter = 'a'; char beginCapitalLetter = 'A'; @@ -71,11 +67,11 @@ public class SimpleSubstitutionCipher { 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); + decoded.append(cipherMap.get(encryptedMessage.charAt(i))); + else decoded.append(encryptedMessage.charAt(i)); } - return decoded; + return decoded.toString(); } /** TODO remove main and make JUnit Testing */ diff --git a/ciphers/Vigenere.java b/Ciphers/Vigenere.java similarity index 95% rename from ciphers/Vigenere.java rename to Ciphers/Vigenere.java index 6fccf91d..86ce52cf 100644 --- a/ciphers/Vigenere.java +++ b/Ciphers/Vigenere.java @@ -1,62 +1,62 @@ -package ciphers; - -/** - * A Java implementation of Vigenere Cipher. - * - * @author straiffix - * @author beingmartinbmc - */ -public class Vigenere { - - public static String encrypt(final String message, final String key) { - - StringBuilder result = new StringBuilder(); - - for (int i = 0, j = 0; i < message.length(); i++) { - char c = message.charAt(i); - if (Character.isLetter(c)) { - if (Character.isUpperCase(c)) { - result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); - - } else { - result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); - } - } else { - result.append(c); - } - j = ++j % key.length(); - } - return result.toString(); - } - - public static String decrypt(final String message, final String key) { - StringBuilder result = new StringBuilder(); - - for (int i = 0, j = 0; i < message.length(); i++) { - - char c = message.charAt(i); - if (Character.isLetter(c)) { - if (Character.isUpperCase(c)) { - result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); - - } else { - result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); - } - } else { - result.append(c); - } - - j = ++j % key.length(); - } - return result.toString(); - } - - public static void main(String[] args) { - String text = "Hello World!"; - String key = "itsakey"; - System.out.println(text); - String ciphertext = encrypt(text, key); - System.out.println(ciphertext); - System.out.println(decrypt(ciphertext, key)); - } -} +package Ciphers; + +/** + * A Java implementation of Vigenere Cipher. + * + * @author straiffix + * @author beingmartinbmc + */ +public class Vigenere { + + public static String encrypt(final String message, final String key) { + + StringBuilder result = new StringBuilder(); + + for (int i = 0, j = 0; i < message.length(); i++) { + char c = message.charAt(i); + if (Character.isLetter(c)) { + if (Character.isUpperCase(c)) { + result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); + + } else { + result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); + } + } else { + result.append(c); + } + j = ++j % key.length(); + } + return result.toString(); + } + + public static String decrypt(final String message, final String key) { + StringBuilder result = new StringBuilder(); + + for (int i = 0, j = 0; i < message.length(); i++) { + + char c = message.charAt(i); + if (Character.isLetter(c)) { + if (Character.isUpperCase(c)) { + result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); + + } else { + result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); + } + } else { + result.append(c); + } + + j = ++j % key.length(); + } + return result.toString(); + } + + public static void main(String[] args) { + String text = "Hello World!"; + String key = "itsakey"; + System.out.println(text); + String ciphertext = encrypt(text, key); + System.out.println(ciphertext); + System.out.println(decrypt(ciphertext, key)); + } +} diff --git a/Code.html b/Code.html deleted file mode 100644 index 346aff0b..00000000 --- a/Code.html +++ /dev/null @@ -1,68 +0,0 @@ -package Misc; -import java.util.Scanner; -/** -* -

Find the Transpose of Matrix!

-Simply take input from the user and -* print the matrix before the transpose and after the transpose. -* -

- * Note: Giving proper comments in your program makes it more user - * friendly and it is assumed as a high quality code. - * - * @author Rajat-Jain29 - * @version 11.0.9 - * @since 2014-03-31 - */ - public class matrixTranspose { - public static void main(String[] args) { - /* - * This is the main method - * - * @param args Unused. - * - * @return Nothing. - */ - Scanner sc = new Scanner(System.in); - int i, j, row, column; - System.out.println("Enter the number of rows in the 2D matrix:"); - /* - * Take input from user for how many rows to be print - */ - row = sc.nextInt(); - System.out.println("Enter the number of columns in the 2D matrix:"); - /* - * Take input from user for how many coloumn to be print - */ - column = sc.nextInt(); - int[][] arr = new int[row][column]; - System.out.println("Enter the elements"); - for (i = 0; i < row; i++) { - for (j = 0; j < column; j++) { - arr[i][j] = sc.nextInt(); - } - } - /* - * Print matrix before the Transpose in proper way - */ - System.out.println("The matrix is:"); - for (i = 0; i < row; i++) { - for (j = 0; j < column; j++) { - System.out.print(arr[i][j] + "\t"); - } - System.out.print("\n"); - } - /* - * Print matrix after the tranpose in proper way Transpose means Interchanging - * of rows wth column so we interchange the rows in next loop Thus at last - * matrix of transpose is obtained through user input... - */ - System.out.println("The Transpose of the given matrix is:"); - for (i = 0; i < column; i++) { - for (j = 0; j < row; j++) { - System.out.print(arr[j][i] + "\t"); - } - System.out.print("\n"); - } - } - } \ No newline at end of file diff --git a/DIRECTORY.md b/DIRECTORY.md index 674542aa..33266c52 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1,12 +1,12 @@ -## 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) +## 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) @@ -96,9 +96,9 @@ * [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) +## DivideAndConquer + * [ClosestPair](https://github.com/TheAlgorithms/Java/blob/master/DivideAndConquer/ClosestPair.java) + * [SkylineAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/DivideAndConquer/SkylineAlgorithm.java) ## DynamicProgramming * [BoardPath](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/BoardPath.java) @@ -227,20 +227,8 @@ * [TwoPointers](https://github.com/TheAlgorithms/Java/blob/master/Others/TwoPointers.java) * [WorstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/WorstFit.java) -## ProjectEuler - * [Problem01](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem01.java) - * [Problem02](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem02.java) - * [Problem03](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem03.java) - * [Problem04](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem04.java) - * [Problem06](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem06.java) - * [Problem07](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem07.java) - * [Problem09](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem09.java) - * [Problem10](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem10.java) - * [Problem12](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem12.java) - ## Searches * [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java) - * [IBSearch test](https://github.com/TheAlgorithms/Java/blob/master/Searches/IBSearch_test.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) @@ -274,15 +262,15 @@ * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java) * [TimSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/TimSort.java) -## strings - * [Alphabetical](https://github.com/TheAlgorithms/Java/blob/master/strings/Alphabetical.java) - * [CharactersSame](https://github.com/TheAlgorithms/Java/blob/master/strings/CharactersSame.java) - * [CheckAnagrams](https://github.com/TheAlgorithms/Java/blob/master/strings/CheckAnagrams.java) - * [CheckVowels](https://github.com/TheAlgorithms/Java/blob/master/strings/CheckVowels.java) - * [HorspoolSearch](https://github.com/TheAlgorithms/Java/blob/master/strings/HorspoolSearch.java) - * [Lower](https://github.com/TheAlgorithms/Java/blob/master/strings/Lower.java) - * [Palindrome](https://github.com/TheAlgorithms/Java/blob/master/strings/Palindrome.java) - * [Pangram](https://github.com/TheAlgorithms/Java/blob/master/strings/Pangram.java) - * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/strings/ReverseString.java) - * [Rotation](https://github.com/TheAlgorithms/Java/blob/master/strings/Rotation.java) - * [Upper](https://github.com/TheAlgorithms/Java/blob/master/strings/Upper.java) +## Strings + * [Alphabetical](https://github.com/TheAlgorithms/Java/blob/master/Strings/Alphabetical.java) + * [CharactersSame](https://github.com/TheAlgorithms/Java/blob/master/Strings/CharactersSame.java) + * [CheckAnagrams](https://github.com/TheAlgorithms/Java/blob/master/Strings/CheckAnagrams.java) + * [CheckVowels](https://github.com/TheAlgorithms/Java/blob/master/Strings/CheckVowels.java) + * [HorspoolSearch](https://github.com/TheAlgorithms/Java/blob/master/Strings/HorspoolSearch.java) + * [Lower](https://github.com/TheAlgorithms/Java/blob/master/Strings/Lower.java) + * [Palindrome](https://github.com/TheAlgorithms/Java/blob/master/Strings/Palindrome.java) + * [Pangram](https://github.com/TheAlgorithms/Java/blob/master/Strings/Pangram.java) + * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Strings/ReverseString.java) + * [Rotation](https://github.com/TheAlgorithms/Java/blob/master/Strings/Rotation.java) + * [Upper](https://github.com/TheAlgorithms/Java/blob/master/Strings/Upper.java) diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java index 09a809a3..01416102 100644 --- a/DataStructures/Graphs/A_Star.java +++ b/DataStructures/Graphs/A_Star.java @@ -2,32 +2,33 @@ Time Complexity = O(E), where E is equal to the number of edges */ -package A_Star; +package Graphs; +import java.lang.reflect.Array; import java.util.*; public class A_Star { private static class Graph { // Graph's structure can be changed only applying changes to this class. - private ArrayList[] graph; + private ArrayList> graph; // Initialise ArrayLists in Constructor public Graph(int size) { - this.graph = new ArrayList[size]; + this.graph = new ArrayList<>(); for (int i = 0; i < size; i++) { - this.graph[i] = new ArrayList<>(); + this.graph.set(i, new ArrayList<>()); } } private ArrayList getNeighbours(int from) { - return this.graph[from]; + return this.graph.get(from); } // Graph is bidirectional, for just one direction remove second instruction of this method. private void addEdge(Edge edge) { - this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); - this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); + this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); + this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); } } @@ -83,7 +84,7 @@ public class A_Star { private void printSolution() { if (this.path != null) System.out.println( - "Optimal path: " + this.path.toString() + ", distance: " + this.distance); + "Optimal path: " + this.path + ", distance: " + this.distance); else System.out.println("There is no path available to connect the points"); } } @@ -129,13 +130,13 @@ public class A_Star { Graph graph = new Graph(20); ArrayList graphData = - new ArrayList<>( - Arrays.asList( - 0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, - null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, - 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, - 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, - 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); + new ArrayList<>( + Arrays.asList( + 0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, + null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, + 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, + 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, + 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); initializeGraph(graph, graphData); PathAndDistance solution = aStar(3, 1, graph, heuristic); @@ -147,10 +148,10 @@ public class A_Star { // estimated value // given by the heuristic function to reach the destination point from the current point. PriorityQueue queue = - new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); + new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); // dummy data to start the algorithm from the beginning point - queue.add(new PathAndDistance(0, new ArrayList<>(Arrays.asList(from)), 0)); + queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0)); boolean solutionFound = false; PathAndDistance currentData = new PathAndDistance(-1, null, -1); diff --git a/DataStructures/HashMap/Hashing/HashMapLinearProbing.java b/DataStructures/HashMap/Hashing/HashMapLinearProbing.java index 62ac6e8b..f381eab7 100644 --- a/DataStructures/HashMap/Hashing/HashMapLinearProbing.java +++ b/DataStructures/HashMap/Hashing/HashMapLinearProbing.java @@ -20,7 +20,7 @@ public class HashMapLinearProbing { public HashMapLinearProbing(int hsize) { this.buckets = new Integer[hsize]; this.hsize = hsize; - this.AVAILABLE = new Integer(Integer.MIN_VALUE); + this.AVAILABLE = Integer.MIN_VALUE; this.size = 0; } @@ -44,7 +44,7 @@ public class HashMapLinearProbing { * @param key the desired key to be inserted in the hash map */ public void insertHash(int key) { - Integer wrappedInt = new Integer(key); + Integer wrappedInt = key; int hash = hashing(key); if (isFull()) { @@ -73,7 +73,7 @@ public class HashMapLinearProbing { * @param key the desired key to be deleted */ public void deleteHash(int key) { - Integer wrappedInt = new Integer(key); + Integer wrappedInt = key; int hash = hashing(key); if (isEmpty()) { @@ -115,7 +115,7 @@ public class HashMapLinearProbing { * @return int the index where the key is located */ public int findHash(int key) { - Integer wrappedInt = new Integer(key); + Integer wrappedInt = key; int hash = hashing(key); if (isEmpty()) { diff --git a/DataStructures/Stacks/README.md b/DataStructures/Stacks/README.md index 9e3b9586..bbf7e9cf 100644 --- a/DataStructures/Stacks/README.md +++ b/DataStructures/Stacks/README.md @@ -2,19 +2,18 @@ stack is an ADT (abstract data type ) that act like list of objects but there is a diffrents. -stack act is *LIFO* (Last In First Out), it means that when we want to get an element from the stack we get the last element in the stack. +stack act is _LIFO_ (Last In First Out), it means that when we want to get an element from the stack we get the last element in the stack. -stack is bast on two methods ( functions) +stack is bast on two methods ( functions) -## push & pop +## push & pop -**push**: add an alement to last index of stack. +**push**: add an alement to last index of stack. for example: we have `1, 3, 5` in stack, then we call push(9), `9` will add to last index of stack -> `1, 3, 5 , 9` - **pop**: remove the last element from stack. for example: we have `1, 3, 5 , 9` in stack, then we call pop(), diff --git a/DataStructures/Trees/AVLSimple b/DataStructures/Trees/AVLSimple index ace0c46b..ea286660 100644 --- a/DataStructures/Trees/AVLSimple +++ b/DataStructures/Trees/AVLSimple @@ -82,7 +82,7 @@ public class AVLTree { System.out.println(this.root.height); } private void display (Node node) { - String str=""; + Strings str=""; if(node.left!=null) str+=node.left.data+"=>"; else diff --git a/divideconquer/ClosestPair.java b/DivideAndConquer/ClosestPair.java similarity index 95% rename from divideconquer/ClosestPair.java rename to DivideAndConquer/ClosestPair.java index 1eeced4e..48cbfc58 100644 --- a/divideconquer/ClosestPair.java +++ b/DivideAndConquer/ClosestPair.java @@ -1,16 +1,15 @@ -package divideconquer; +package DivideAndConquer; + +import java.io.IOException; /** * For a set of points in a coordinates system (10000 maximum), ClosestPair class calculates the two * closest points. - * - * @author: anonymous - * @author: Marisa Afuera */ public final class ClosestPair { /** Number of points */ - int numberPoints = 0; + int numberPoints; /** Input data, maximum 10000. */ private Location[] array; /** Minimum point coordinate. */ @@ -40,8 +39,8 @@ public final class ClosestPair { /** Location class is an auxiliary type to keep points coordinates. */ public static class Location { - double x = 0; - double y = 0; + double x; + double y; /** * @param xpar (IN Parameter) x coordinate
@@ -172,9 +171,9 @@ public final class ClosestPair { // divide-right array System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); - double minLeftArea = 0; // Minimum length of left array - double minRightArea = 0; // Minimum length of right array - double minValue = 0; // Minimum lengt + double minLeftArea; // Minimum length of left array + double minRightArea; // Minimum length of right array + double minValue; // Minimum lengt minLeftArea = closestPair(leftArray, divideX); // recursive closestPair minRightArea = closestPair(rightArray, indexNum - divideX); @@ -209,7 +208,7 @@ public final class ClosestPair { } yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates /* Coordinates in Window */ - double length = 0; + double length; // size comparison within window for (int i = 0; i < secondCount - 1; i++) { for (int j = (i + 1); j < secondCount; j++) { @@ -246,9 +245,9 @@ public final class ClosestPair { public double bruteForce(final Location[] arrayParam) { double minValue = Double.MAX_VALUE; // minimum distance - double length = 0; - double xGap = 0; // Difference between x coordinates - double yGap = 0; // Difference between y coordinates + double length; + double xGap; // Difference between x coordinates + double yGap; // Difference between y coordinates double result = 0; if (arrayParam.length == 2) { @@ -297,7 +296,6 @@ public final class ClosestPair { * main function: execute class. * * @param args (IN Parameter)
- * @throws IOException If an input or output exception occurred */ public static void main(final String[] args) { diff --git a/divideconquer/SkylineAlgorithm.java b/DivideAndConquer/SkylineAlgorithm.java similarity index 96% rename from divideconquer/SkylineAlgorithm.java rename to DivideAndConquer/SkylineAlgorithm.java index e5f280f0..3e027fd7 100644 --- a/divideconquer/SkylineAlgorithm.java +++ b/DivideAndConquer/SkylineAlgorithm.java @@ -1,169 +1,169 @@ -package divideconquer; - -import java.util.ArrayList; -import java.util.Comparator; - -/** - * @author dimgrichr - *

Space complexity: O(n) Time complexity: O(nlogn), because it is a divide and conquer - * algorithm - */ -public class SkylineAlgorithm { - private ArrayList points; - - /** - * Main constructor of the application. ArrayList points gets created, which represents the sum of - * all edges. - */ - public SkylineAlgorithm() { - points = new ArrayList<>(); - } - - /** @return points, the ArrayList that includes all points. */ - public ArrayList getPoints() { - return points; - } - - /** - * The main divide and conquer, and also recursive algorithm. It gets an ArrayList full of points - * as an argument. If the size of that ArrayList is 1 or 2, the ArrayList is returned as it is, or - * with one less point (if the initial size is 2 and one of it's points, is dominated by the other - * one). On the other hand, if the ArrayList's size is bigger than 2, the function is called - * again, twice, with arguments the corresponding half of the initial ArrayList each time. Once - * the flashback has ended, the function produceFinalSkyLine gets called, in order to produce the - * final skyline, and return it. - * - * @param list, the initial list of points - * @return leftSkyLine, the combination of first half's and second half's skyline - * @see Point - */ - public ArrayList produceSubSkyLines(ArrayList list) { - - // part where function exits flashback - int size = list.size(); - if (size == 1) { - return list; - } else if (size == 2) { - if (list.get(0).dominates(list.get(1))) { - list.remove(1); - } else { - if (list.get(1).dominates(list.get(0))) { - list.remove(0); - } - } - return list; - } - - // recursive part of the function - ArrayList leftHalf = new ArrayList<>(); - ArrayList rightHalf = new ArrayList<>(); - for (int i = 0; i < list.size(); i++) { - if (i < list.size() / 2) { - leftHalf.add(list.get(i)); - } else { - rightHalf.add(list.get(i)); - } - } - ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf); - ArrayList rightSubSkyLine = produceSubSkyLines(rightHalf); - - // skyline is produced - return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); - } - - /** - * The first half's skyline gets cleared from some points that are not part of the final skyline - * (Points with same x-value and different y=values. The point with the smallest y-value is kept). - * Then, the minimum y-value of the points of first half's skyline is found. That helps us to - * clear the second half's skyline, because, the points of second half's skyline that have greater - * y-value of the minimum y-value that we found before, are dominated, so they are not part of the - * final skyline. Finally, the "cleaned" first half's and second half's skylines, are combined, - * producing the final skyline, which is returned. - * - * @param left the skyline of the left part of points - * @param right the skyline of the right part of points - * @return left the final skyline - */ - public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { - - // dominated points of ArrayList left are removed - for (int i = 0; i < left.size() - 1; i++) { - if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { - left.remove(i); - i--; - } - } - - // minimum y-value is found - int min = left.get(0).y; - for (int i = 1; i < left.size(); i++) { - if (min > left.get(i).y) { - min = left.get(i).y; - if (min == 1) { - i = left.size(); - } - } - } - - // dominated points of ArrayList right are removed - for (int i = 0; i < right.size(); i++) { - if (right.get(i).y >= min) { - right.remove(i); - i--; - } - } - - // final skyline found and returned - left.addAll(right); - return left; - } - - public static class Point { - private int x; - private int y; - - /** - * The main constructor of Point Class, used to represent the 2 Dimension points. - * - * @param x the point's x-value. - * @param y the point's y-value. - */ - public Point(int x, int y) { - this.x = x; - this.y = y; - } - - /** @return x, the x-value */ - public int getX() { - return x; - } - - /** @return y, the y-value */ - public int getY() { - return y; - } - - /** - * Based on the skyline theory, it checks if the point that calls the function dominates the - * argument point. - * - * @param p1 the point that is compared - * @return true if the point wich calls the function dominates p1 false otherwise. - */ - public boolean dominates(Point p1) { - // checks if p1 is dominated - return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y); - } - } - - /** - * It is used to compare the 2 Dimension points, based on their x-values, in order get sorted - * later. - */ - class XComparator implements Comparator { - @Override - public int compare(Point a, Point b) { - return Integer.compare(a.x, b.x); - } - } -} +package DivideAndConquer; + +import java.util.ArrayList; +import java.util.Comparator; + +/** + * @author dimgrichr + *

Space complexity: O(n) Time complexity: O(nlogn), because it is a divide and conquer + * algorithm + */ +public class SkylineAlgorithm { + private ArrayList points; + + /** + * Main constructor of the application. ArrayList points gets created, which represents the sum of + * all edges. + */ + public SkylineAlgorithm() { + points = new ArrayList<>(); + } + + /** @return points, the ArrayList that includes all points. */ + public ArrayList getPoints() { + return points; + } + + /** + * The main divide and conquer, and also recursive algorithm. It gets an ArrayList full of points + * as an argument. If the size of that ArrayList is 1 or 2, the ArrayList is returned as it is, or + * with one less point (if the initial size is 2 and one of it's points, is dominated by the other + * one). On the other hand, if the ArrayList's size is bigger than 2, the function is called + * again, twice, with arguments the corresponding half of the initial ArrayList each time. Once + * the flashback has ended, the function produceFinalSkyLine gets called, in order to produce the + * final skyline, and return it. + * + * @param list, the initial list of points + * @return leftSkyLine, the combination of first half's and second half's skyline + * @see Point + */ + public ArrayList produceSubSkyLines(ArrayList list) { + + // part where function exits flashback + int size = list.size(); + if (size == 1) { + return list; + } else if (size == 2) { + if (list.get(0).dominates(list.get(1))) { + list.remove(1); + } else { + if (list.get(1).dominates(list.get(0))) { + list.remove(0); + } + } + return list; + } + + // recursive part of the function + ArrayList leftHalf = new ArrayList<>(); + ArrayList rightHalf = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + if (i < list.size() / 2) { + leftHalf.add(list.get(i)); + } else { + rightHalf.add(list.get(i)); + } + } + ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf); + ArrayList rightSubSkyLine = produceSubSkyLines(rightHalf); + + // skyline is produced + return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); + } + + /** + * The first half's skyline gets cleared from some points that are not part of the final skyline + * (Points with same x-value and different y=values. The point with the smallest y-value is kept). + * Then, the minimum y-value of the points of first half's skyline is found. That helps us to + * clear the second half's skyline, because, the points of second half's skyline that have greater + * y-value of the minimum y-value that we found before, are dominated, so they are not part of the + * final skyline. Finally, the "cleaned" first half's and second half's skylines, are combined, + * producing the final skyline, which is returned. + * + * @param left the skyline of the left part of points + * @param right the skyline of the right part of points + * @return left the final skyline + */ + public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { + + // dominated points of ArrayList left are removed + for (int i = 0; i < left.size() - 1; i++) { + if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { + left.remove(i); + i--; + } + } + + // minimum y-value is found + int min = left.get(0).y; + for (int i = 1; i < left.size(); i++) { + if (min > left.get(i).y) { + min = left.get(i).y; + if (min == 1) { + i = left.size(); + } + } + } + + // dominated points of ArrayList right are removed + for (int i = 0; i < right.size(); i++) { + if (right.get(i).y >= min) { + right.remove(i); + i--; + } + } + + // final skyline found and returned + left.addAll(right); + return left; + } + + public static class Point { + private int x; + private int y; + + /** + * The main constructor of Point Class, used to represent the 2 Dimension points. + * + * @param x the point's x-value. + * @param y the point's y-value. + */ + public Point(int x, int y) { + this.x = x; + this.y = y; + } + + /** @return x, the x-value */ + public int getX() { + return x; + } + + /** @return y, the y-value */ + public int getY() { + return y; + } + + /** + * Based on the skyline theory, it checks if the point that calls the function dominates the + * argument point. + * + * @param p1 the point that is compared + * @return true if the point wich calls the function dominates p1 false otherwise. + */ + public boolean dominates(Point p1) { + // checks if p1 is dominated + return (this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y); + } + } + + /** + * It is used to compare the 2 Dimension points, based on their x-values, in order get sorted + * later. + */ + class XComparator implements Comparator { + @Override + public int compare(Point a, Point b) { + return Integer.compare(a.x, b.x); + } + } +} diff --git a/ProjectEuler/Problem01.java b/ProjectEuler/Problem01.java deleted file mode 100644 index a19876f8..00000000 --- a/ProjectEuler/Problem01.java +++ /dev/null @@ -1,51 +0,0 @@ -package ProjectEuler; - -/** - * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. - * The sum of these multiples is 23. - * - *

Find the sum of all the multiples of 3 or 5 below 1000. - * - *

Link: https://projecteuler.net/problem=1 - */ -public class Problem01 { - public static void main(String[] args) { - int[][] testNumber = { - {3, 0}, - {4, 3}, - {10, 23}, - {1000, 233168}, - {-1, 0} - }; - - for (int[] ints : testNumber) { - assert solution1(ints[0]) == ints[1]; - assert solution2(ints[0]) == ints[1]; - } - } - - private static int solution1(int n) { - int sum = 0; - for (int i = 3; i < n; ++i) { - if (i % 3 == 0 || i % 5 == 0) { - sum += i; - } - } - return sum; - } - - private static int solution2(int n) { - int sum = 0; - - int terms = (n - 1) / 3; - sum += terms * (6 + (terms - 1) * 3) / 2; - - terms = (n - 1) / 5; - sum += terms * (10 + (terms - 1) * 5) / 2; - - terms = (n - 1) / 15; - sum -= terms * (30 + (terms - 1) * 15) / 2; - - return sum; - } -} diff --git a/ProjectEuler/Problem02.java b/ProjectEuler/Problem02.java deleted file mode 100644 index 2d67c54f..00000000 --- a/ProjectEuler/Problem02.java +++ /dev/null @@ -1,43 +0,0 @@ -package ProjectEuler; - -/** - * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By - * starting with 1 and 2, the first 10 terms will be: - * - *

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... - * - *

By considering the terms in the Fibonacci sequence whose values do not exceed four million, - * find the sum of the even-valued terms. - * - *

Link: https://projecteuler.net/problem=2 - */ -public class Problem02 { - public static void main(String[] args) { - int[][] testNumbers = { - {10, 10}, /* 2 + 8 == 10 */ - {15, 10}, /* 2 + 8 == 10 */ - {2, 2}, - {1, 0}, - {89, 44} /* 2 + 8 + 34 == 44 */ - }; - - for (int[] ints : testNumbers) { - assert solution1(ints[0]) == ints[1]; - } - } - - private static int solution1(int n) { - int sum = 0; - int first = 1; - int second = 2; - while (second <= n) { - if (second % 2 == 0) { - sum += second; - } - int temp = first + second; - first = second; - second = temp; - } - return sum; - } -} diff --git a/ProjectEuler/Problem03.java b/ProjectEuler/Problem03.java deleted file mode 100644 index 31d6fdc4..00000000 --- a/ProjectEuler/Problem03.java +++ /dev/null @@ -1,62 +0,0 @@ -package ProjectEuler; - -/** - * The prime factors of 13195 are 5, 7, 13 and 29. - * - *

What is the largest prime factor of the number 600851475143 ? - * - *

Link: https://projecteuler.net/problem=3 - */ -public class Problem03 { - - /** - * Checks if a number is prime or not - * - * @param n the number - * @return {@code true} if {@code n} is prime - */ - public static boolean isPrime(int n) { - if (n == 2) { - return true; - } - if (n < 2 || n % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { - if (n % i == 0) { - return false; - } - } - return true; - } - - /** - * Calculate all the prime factors of a number and return the largest - * - * @param n integer number - * @return the maximum prime factor of the given number - */ - static long maxPrimeFactor(long n) { - for (int i = 2; i < n / 2; i++) { - if (isPrime(i)) - while (n % i == 0) { - n /= i; - } - } - return n; - } - - public static void main(String[] args) { - int[][] testNumbers = { - {87, 29}, - {10, 5}, - {21, 7}, - {657, 73}, - {777, 37} - }; - for (int[] num : testNumbers) { - assert Problem03.maxPrimeFactor(num[0]) == num[1]; - } - assert Problem03.maxPrimeFactor(600851475143L) == 6857; - } -} diff --git a/ProjectEuler/Problem04.java b/ProjectEuler/Problem04.java deleted file mode 100644 index 9f9a84bd..00000000 --- a/ProjectEuler/Problem04.java +++ /dev/null @@ -1,41 +0,0 @@ -package ProjectEuler; - -/** - * A palindromic number reads the same both ways. The largest palindrome made from the product of - * two 2-digit numbers is 9009 = 91 × 99. - * - *

Find the largest palindrome made from the product of two 3-digit numbers. - * - *

link: https://projecteuler.net/problem=4 - */ -public class Problem04 { - public static void main(String[] args) { - - assert solution1(10000) == -1; - assert solution1(20000) == 19591; /* 19591 == 143*137 */ - assert solution1(30000) == 29992; /* 29992 == 184*163 */ - assert solution1(40000) == 39893; /* 39893 == 287*139 */ - assert solution1(50000) == 49894; /* 49894 == 494*101 */ - assert solution1(60000) == 59995; /* 59995 == 355*169 */ - assert solution1(70000) == 69996; /* 69996 == 614*114 */ - assert solution1(80000) == 79897; /* 79897 == 733*109 */ - assert solution1(90000) == 89798; /* 89798 == 761*118 */ - assert solution1(100000) == 99999; /* 100000 == 813*123 */ - } - - private static int solution1(int n) { - for (int i = n - 1; i >= 10000; --i) { - String strNumber = String.valueOf(i); - - /* Test if strNumber is palindrome */ - if (new StringBuilder(strNumber).reverse().toString().equals(strNumber)) { - for (int divisor = 999; divisor >= 100; --divisor) { - if (i % divisor == 0 && String.valueOf(i / divisor).length() == 3) { - return i; - } - } - } - } - return -1; /* not found */ - } -} diff --git a/ProjectEuler/Problem06.java b/ProjectEuler/Problem06.java deleted file mode 100644 index 0c1fbecd..00000000 --- a/ProjectEuler/Problem06.java +++ /dev/null @@ -1,42 +0,0 @@ -package ProjectEuler; - -/** - * The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The - * square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence - * the difference between the sum of the squares of the first ten natural numbers and the square of - * the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first N - * natural numbers and the square of the sum. - * - *

link: https://projecteuler.net/problem=6 - */ -public class Problem06 { - public static void main(String[] args) { - int[][] testNumbers = { - {10, 2640}, - {15, 13160}, - {20, 41230}, - {50, 1582700} - }; - - for (int[] testNumber : testNumbers) { - assert solution1(testNumber[0]) == testNumber[1] - && solutions2(testNumber[0]) == testNumber[1]; - } - } - - private static int solution1(int n) { - int sum1 = 0; - int sum2 = 0; - for (int i = 1; i <= n; ++i) { - sum1 += i * i; - sum2 += i; - } - return sum2 * sum2 - sum1; - } - - private static int solutions2(int n) { - int sumOfSquares = n * (n + 1) * (2 * n + 1) / 6; - int squareOfSum = (int) Math.pow((n * (n + 1) / 2.0), 2); - return squareOfSum - sumOfSquares; - } -} diff --git a/ProjectEuler/Problem07.java b/ProjectEuler/Problem07.java deleted file mode 100644 index 25df143c..00000000 --- a/ProjectEuler/Problem07.java +++ /dev/null @@ -1,60 +0,0 @@ -package ProjectEuler; - -/** - * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is - * 13. - * - *

What is the 10 001st prime number? - * - *

link: https://projecteuler.net/problem=7 - */ -public class Problem07 { - public static void main(String[] args) { - int[][] testNumbers = { - {1, 2}, - {2, 3}, - {3, 5}, - {4, 7}, - {5, 11}, - {6, 13}, - {20, 71}, - {50, 229}, - {100, 541} - }; - for (int[] number : testNumbers) { - assert solution1(number[0]) == number[1]; - } - } - - /*** - * Checks if a number is prime or not - * @param number the number - * @return {@code true} if {@code number} is prime - */ - private static boolean isPrime(int number) { - if (number == 2) { - return true; - } - if (number < 2 || number % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(number); i <= limit; i += 2) { - if (number % i == 0) { - return false; - } - } - return true; - } - - private static int solution1(int n) { - int count = 0; - int number = 1; - - while (count != n) { - if (isPrime(++number)) { - count++; - } - } - return number; - } -} diff --git a/ProjectEuler/Problem09.java b/ProjectEuler/Problem09.java deleted file mode 100644 index b0dbebb9..00000000 --- a/ProjectEuler/Problem09.java +++ /dev/null @@ -1,28 +0,0 @@ -package ProjectEuler; - -/** - * A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, - * - *

a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. - * - *

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. - * - *

link: https://projecteuler.net/problem=9 - */ -public class Problem09 { - public static void main(String[] args) { - assert solution1() == 31875000; - } - - private static int solution1() { - for (int i = 0; i <= 300; ++i) { - for (int j = 0; j <= 400; ++j) { - int k = 1000 - i - j; - if (i * i + j * j == k * k) { - return i * j * k; - } - } - } - return -1; /* should not happen */ - } -} diff --git a/ProjectEuler/Problem10.java b/ProjectEuler/Problem10.java deleted file mode 100644 index a51a2228..00000000 --- a/ProjectEuler/Problem10.java +++ /dev/null @@ -1,55 +0,0 @@ -package ProjectEuler; - -/** - * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. - * - *

Find the sum of all the primes below two million. - * - *

link: https://projecteuler.net/problem=10 - */ -public class Problem10 { - public static void main(String[] args) { - long[][] testNumbers = { - {2000000, 142913828922L}, - {10000, 5736396}, - {5000, 1548136}, - {1000, 76127}, - {10, 17}, - {7, 10} - }; - - for (long[] testNumber : testNumbers) { - assert solution1(testNumber[0]) == testNumber[1]; - } - } - - /*** - * Checks if a number is prime or not - * @param n the number - * @return {@code true} if {@code n} is prime - */ - private static boolean isPrime(int n) { - if (n == 2) { - return true; - } - if (n < 2 || n % 2 == 0) { - return false; - } - for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { - if (n % i == 0) { - return false; - } - } - return true; - } - - private static long solution1(long n) { - long sum = 0; - for (int i = 2; i < n; ++i) { - if (isPrime(i)) { - sum += i; - } - } - return sum; - } -} diff --git a/ProjectEuler/Problem12.java b/ProjectEuler/Problem12.java deleted file mode 100644 index 9743bc9d..00000000 --- a/ProjectEuler/Problem12.java +++ /dev/null @@ -1,54 +0,0 @@ -package ProjectEuler; -/** - * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle - * number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: - * - *

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... - * - *

Let us list the factors of the first seven triangle numbers: - * - *

1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see - * that 28 is the first triangle number to have over five divisors. - * - *

What is the value of the first triangle number to have over five hundred divisors? - * - *

link: https://projecteuler.net/problem=12 - */ -public class Problem12 { - - /** Driver Code */ - public static void main(String[] args) { - assert solution1(500) == 76576500; - } - - /* returns the nth triangle number; that is, the sum of all the natural numbers less than, or equal to, n */ - public static int triangleNumber(int n) { - int sum = 0; - for (int i = 0; i <= n; i++) sum += i; - return sum; - } - - public static int solution1(int number) { - int j = 0; // j represents the jth triangle number - int n = 0; // n represents the triangle number corresponding to j - int numberOfDivisors = 0; // number of divisors for triangle number n - - while (numberOfDivisors <= number) { - - // resets numberOfDivisors because it's now checking a new triangle number - // and also sets n to be the next triangle number - numberOfDivisors = 0; - j++; - n = triangleNumber(j); - - // for every number from 1 to the square root of this triangle number, - // count the number of divisors - for (int i = 1; i <= Math.sqrt(n); i++) if (n % i == 0) numberOfDivisors++; - - // 1 to the square root of the number holds exactly half of the divisors - // so multiply it by 2 to include the other corresponding half - numberOfDivisors *= 2; - } - return n; - } -} diff --git a/README-ko.md b/README-ko.md index cd3bac47..487d80e9 100644 --- a/README-ko.md +++ b/README-ko.md @@ -156,28 +156,28 @@ From [Wikipedia][binary-wiki]: 이진 탐색, (also known as half-interval searc ## 나머지 알고리즘에 대한 링크 -| 전환 | 다이나믹프로그래밍(DP) | 암호 | 그 외 것들 | -| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------- | -| [Any Base to Any Base](Conversions/AnyBaseToAnyBase.java) | [Coin Change](Dynamic%20Programming/CoinChange.java) | [Caesar](ciphers/Caesar.java) | [Heap Sort](misc/heap_sort.java) | -| [Any Base to Decimal](Conversions/AnyBaseToDecimal.java) | [Egg Dropping](Dynamic%20Programming/EggDropping.java) | [Columnar Transposition Cipher](ciphers/ColumnarTranspositionCipher.java) | [Palindromic Prime Checker](misc/PalindromicPrime.java) | -| [Binary to Decimal](Conversions/BinaryToDecimal.java) | [Fibonacci](Dynamic%20Programming/Fibonacci.java) | [RSA](ciphers/RSA.java) | More soon... | -| [Binary to HexaDecimal](Conversions/BinaryToHexadecimal.java) | [Kadane Algorithm](Dynamic%20Programming/KadaneAlgorithm.java) | more coming soon... | -| [Binary to Octal](Conversions/BinaryToOctal.java) | [Knapsack](Dynamic%20Programming/Knapsack.java) | -| [Decimal To Any Base](Conversions/DecimalToAnyBase.java) | [Longest Common Subsequence](Dynamic%20Programming/LongestCommonSubsequence.java) | -| [Decimal To Binary](Conversions/DecimalToBinary.java) | [Longest Increasing Subsequence](Dynamic%20Programming/LongestIncreasingSubsequence.java) | -| [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java) | [Rod Cutting](Dynamic%20Programming/RodCutting.java) | -| and much more... | and more... | +| 전환 | 다이나믹프로그래밍(DP) | 암호 | 그 외 것들 | +| --------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------ | +| [Any Base to Any Base](Conversions/AnyBaseToAnyBase.java) | [Coin Change](DynamicProgramming/CoinChange.java) | [Caesar](Ciphers/Caesar.java) | [Heap Sort](Sorts/HeapSort.java) | +| [Any Base to Decimal](Conversions/AnyBaseToDecimal.java) | [Egg Dropping](DynamicProgramming/EggDropping.java) | [Columnar Transposition Cipher](Ciphers/ColumnarTranspositionCipher.java) | [Palindromic Prime Checker](Misc/PalindromePrime.java) | +| [Binary to Decimal](Conversions/BinaryToDecimal.java) | [Fibonacci](DynamicProgramming/Fibonacci.java) | [RSA](Ciphers/RSA.java) | More soon... | +| [Binary to HexaDecimal](Conversions/BinaryToHexadecimal.java) | [Kadane Algorithm](DynamicProgramming/KadaneAlgorithm.java) | more coming soon... | +| [Binary to Octal](Conversions/BinaryToOctal.java) | [Knapsack](DynamicProgramming/Knapsack.java) | +| [Decimal To Any Base](Conversions/DecimalToAnyBase.java) | [Longest Common Subsequence](DynamicProgramming/LongestCommonSubsequence.java) | +| [Decimal To Binary](Conversions/DecimalToBinary.java) | [Longest Increasing Subsequence](DynamicProgramming/LongestIncreasingSubsequence.java) | +| [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java) | [Rod Cutting](DynamicProgramming/RodCutting.java) | +| and much more... | and more... | ### 자료 구조 -| 그래프 | 힙 | 리스트 | 큐 | -| ----------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- | -| [너비우선탐색](DataStructures/Graphs/BFS.java) | [빈 힙 예외처리](DataStructures/Heaps/EmptyHeapException.java) | [원형 연결리스트](DataStructures/Lists/CircleLinkedList.java) | [제너릭 어레이 리스트 큐](DataStructures/Queues/GenericArrayListQueue.java) | -| [깊이우선탐색](DataStructures/Graphs/DFS.java) | [힙](DataStructures/Heaps/Heap.java) | [이중 연결리스트](DataStructures/Lists/DoublyLinkedList.java) | [큐](DataStructures/Queues/Queues.java) | -| [그래프](DataStructures/Graphs/Graphs.java) | [힙 요소](DataStructures/Heaps/HeapElement.java) | [단순 연결리스트](DataStructures/Lists/SinglyLinkedList.java) | -| [크루스칼 알고리즘](DataStructures/Graphs/KruskalsAlgorithm.java) | [최대힙](Data%Structures/Heaps/MaxHeap.java) | -| [행렬 그래프](DataStructures/Graphs/MatrixGraphs.java) | [최소힙](DataStructures/Heaps/MinHeap.java) | -| [프림 최소신장트리](DataStructures/Graphs/PrimMST.java) | +| 그래프 | 힙 | 리스트 | 큐 | +| ------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- | +| | [빈 힙 예외처리](DataStructures/Heaps/EmptyHeapException.java) | [원형 연결리스트](DataStructures/Lists/CircleLinkedList.java) | [제너릭 어레이 리스트 큐](DataStructures/Queues/GenericArrayListQueue.java) | +| | [힙](DataStructures/Heaps/Heap.java) | [이중 연결리스트](DataStructures/Lists/DoublyLinkedList.java) | [큐](DataStructures/Queues/Queues.java) | +| [그래프](DataStructures/Graphs/Graphs.java) | [힙 요소](DataStructures/Heaps/HeapElement.java) | [단순 연결리스트](DataStructures/Lists/SinglyLinkedList.java) | +| [크루스칼 알고리즘](DataStructures/Graphs/Kruskal.java) | [최대힙](DataStructures/Heaps/MaxHeap.java) | +| [행렬 그래프](DataStructures/Graphs/MatrixGraphs.java) | [최소힙](DataStructures/Heaps/MinHeap.java) | +| [프림 최소신장트리](DataStructures/Graphs/PrimMST.java) | | 스택 | 트리 | | --------------------------------------------------------------- | ------------------------------------------------- | @@ -187,5 +187,5 @@ From [Wikipedia][binary-wiki]: 이진 탐색, (also known as half-interval searc - [Bags](DataStructures/Bags/Bag.java) - [Buffer](DataStructures/Buffers/CircularBuffer.java) -- [HashMap](DataStructures/HashMap/HashMap.java) -- [Matrix](DataStructures/Matrix/Matrix.java) +- [HashMap](DataStructures/HashMap/Hashing/HashMap.java) +- diff --git a/README.md b/README.md index 5cba56a4..59930fde 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ -[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) - # The Algorithms - Java -[![Build Status](https://api.travis-ci.com/TheAlgorithms/Java.svg?branch=master)](https://travis-ci.com/TheAlgorithms/Java)  -[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100) -[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6)  -[![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)  + +[![Build](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml) +[![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6) +[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) You can run and edit the algorithms, or contribute to them using Gitpod.io (a free online development environment) with a single click. diff --git a/REVIEWER.md b/REVIEWER.md deleted file mode 100644 index 607b51e3..00000000 --- a/REVIEWER.md +++ /dev/null @@ -1,13 +0,0 @@ -# Guidelines for reviewers and maintainers - -Following are some guidelines for contributors who are providing reviews to the pull-requests. - -1. On any given pull-request, there only one reviewer should be active at a time. Once the reviewer is done, others may add short comments or any further reviews as needed. Again, one at a time. -2. Assigning reviewers should be avoided unless the pull-request is for a particular task the reviewer is more proficient in. -3. Any contributor who has had their code merged into the repo can provide with reviews as they have gone through the repo standards at least once before. The reviewer will be on a first-come-first serve basis. -4. Most repositories have a check-list in the description for pull-requests. Many times, the contributors are not following them and simply remove the checklist or checkthem without taking the time to review the checklist items. These contributors are almost always copying the code from somewhere. These should be pointed out politely and reviews should be blocked until the contributor updates the basic code structure per the checklist and the repo standards. -5. The reviewers should label every pull-request appropriately - including "invalid" as the case may be. -6. Some pull-requests have existing duplicate code or duplicate pull-requests or sometimes, a novice might create a new pull-request for every new commit. This is a daunting task but one of the responsibility of a reviewer. -7. Discourage creating branches on the repo but rather fork the repo to the respective userspace and contribute from that fork. -8. Some repos - C & C++ - have collaboration with GitPod wherein the code and the contribution can be executed and tested online with relative simplicity. It also contains tools necessary to perform debug and CI checks without installing any tools. Encourage contributors to utilize the feature. Reviewers can test the contributed algorithms online without worrying about forks and branches. -9. There should not be any hurry to merge pull-requests. Since the repos are educational, better to get the contributions right even if it takes a bit longer to review. Encourage patience and develop debugging skills of contributors. \ No newline at end of file diff --git a/Searches/IBSearch_test.java b/Searches/IBSearch_test.java deleted file mode 100644 index b1fe99dd..00000000 --- a/Searches/IBSearch_test.java +++ /dev/null @@ -1,32 +0,0 @@ -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -public class IterativeBinarySearch_Test { - - // kiem thu luong du lieu - // ham search dung de tim key trong mang da xap xep - // dua theo tieu chi all-du path tim dc 4 tescase - Integer[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - IterativeBinarySearch search = new IterativeBinarySearch(); - - @Test - void tc1_key_khong_co_trong_mang() { - assertTrue(search.find(arr, 11) == -1); - } - - @Test - void tc2_key_nam_chinh_giua_mang() { - assertTrue(search.find(arr, 5) == 5); - } - - @Test - void tc3_key_nam_cuoi_mang() { - assertTrue(search.find(arr, 10) == 10); - } - - @Test - void tc4_key_nam_dau_mang() { - assertTrue(search.find(arr, 0) == 0); - } -} diff --git a/strings/Alphabetical.java b/Strings/Alphabetical.java similarity index 98% rename from strings/Alphabetical.java rename to Strings/Alphabetical.java index 67620eae..366b59fe 100644 --- a/strings/Alphabetical.java +++ b/Strings/Alphabetical.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** * Alphabetical order is a system whereby character strings are placed in order based on the diff --git a/strings/CharactersSame.java b/Strings/CharactersSame.java similarity index 97% rename from strings/CharactersSame.java rename to Strings/CharactersSame.java index 26ccbd4f..5c4b5b4a 100644 --- a/strings/CharactersSame.java +++ b/Strings/CharactersSame.java @@ -1,4 +1,4 @@ -package strings; +package Strings; public class CharactersSame { diff --git a/strings/CheckAnagrams.java b/Strings/CheckAnagrams.java similarity index 98% rename from strings/CheckAnagrams.java rename to Strings/CheckAnagrams.java index 95e68e10..1bbeed40 100644 --- a/strings/CheckAnagrams.java +++ b/Strings/CheckAnagrams.java @@ -1,4 +1,4 @@ -package strings; +package Strings; import java.util.HashMap; import java.util.Map; diff --git a/strings/CheckVowels.java b/Strings/CheckVowels.java similarity index 96% rename from strings/CheckVowels.java rename to Strings/CheckVowels.java index 362bd7ac..d9ad0b7b 100644 --- a/strings/CheckVowels.java +++ b/Strings/CheckVowels.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** * Vowel Count is a system whereby character strings are placed in order based on the position of @@ -33,7 +33,7 @@ class CheckVowels { * @param input a string prints the count of vowels */ public static void countVowels(String input) { - input.toLowerCase(); + input = input.toLowerCase(); int count = 0; int i = 0; while (i < input.length()) { diff --git a/strings/HorspoolSearch.java b/Strings/HorspoolSearch.java similarity index 99% rename from strings/HorspoolSearch.java rename to Strings/HorspoolSearch.java index 694db017..880633a8 100644 --- a/strings/HorspoolSearch.java +++ b/Strings/HorspoolSearch.java @@ -1,4 +1,4 @@ -package strings; +package Strings; import java.util.HashMap; diff --git a/strings/Lower.java b/Strings/Lower.java similarity index 97% rename from strings/Lower.java rename to Strings/Lower.java index 4746e787..203fddf5 100644 --- a/strings/Lower.java +++ b/Strings/Lower.java @@ -1,4 +1,4 @@ -package strings; +package Strings; public class Lower { diff --git a/strings/Palindrome.java b/Strings/Palindrome.java similarity index 99% rename from strings/Palindrome.java rename to Strings/Palindrome.java index 9f77b4c3..5457eaa3 100644 --- a/strings/Palindrome.java +++ b/Strings/Palindrome.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** Wikipedia: https://en.wikipedia.org/wiki/Palindrome */ class Palindrome { diff --git a/strings/Pangram.java b/Strings/Pangram.java similarity index 98% rename from strings/Pangram.java rename to Strings/Pangram.java index 27fce85a..e434d50c 100644 --- a/strings/Pangram.java +++ b/Strings/Pangram.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** Wikipedia: https://en.wikipedia.org/wiki/Pangram */ public class Pangram { diff --git a/strings/ReverseString.java b/Strings/ReverseString.java similarity index 98% rename from strings/ReverseString.java rename to Strings/ReverseString.java index bcbe6925..8a4d7962 100644 --- a/strings/ReverseString.java +++ b/Strings/ReverseString.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** Reverse String using different version */ public class ReverseString { diff --git a/strings/Rotation.java b/Strings/Rotation.java similarity index 98% rename from strings/Rotation.java rename to Strings/Rotation.java index e855626b..4ee1cb1c 100644 --- a/strings/Rotation.java +++ b/Strings/Rotation.java @@ -1,4 +1,4 @@ -package strings; +package Strings; /** * Given a string, moving several characters in front of the string to the end of the string. For diff --git a/strings/Upper.java b/Strings/Upper.java similarity index 97% rename from strings/Upper.java rename to Strings/Upper.java index 22becbf4..4367d8b6 100644 --- a/strings/Upper.java +++ b/Strings/Upper.java @@ -1,4 +1,4 @@ -package strings; +package Strings; public class Upper {