Cleanup build errors

This commit is contained in:
Andrii Siriak 2021-09-26 10:57:21 +03:00
parent 96b66c7759
commit 3dc5378417
No known key found for this signature in database
GPG Key ID: 165FBC99465D381C
39 changed files with 370 additions and 949 deletions

View File

@ -1,5 +1,7 @@
name: 'Close stale issues and PRs' name: 'Close stale issues and PRs'
on: push on:
schedule:
- cron: '0 0 * * *'
jobs: jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -12,6 +14,5 @@ jobs:
close-pr-message: 'Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' close-pr-message: 'Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!'
exempt-issue-labels: 'dont-close' exempt-issue-labels: 'dont-close'
exempt-pr-labels: 'dont-close' exempt-pr-labels: 'dont-close'
days-before-stale: 3 days-before-stale: 30
days-before-close: 0 days-before-close: 7
operations-per-run: 500

View File

@ -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? ## How to contribute?
#### **Did you find a bug?** #### **Did you find a bug?**

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.Scanner; import java.util.Scanner;
@ -215,30 +215,26 @@ public class AES {
/** /**
* Subroutine of the Rijndael key expansion. * Subroutine of the Rijndael key expansion.
*
* @param t
* @param rconCounter
* @return
*/ */
public static BigInteger scheduleCore(BigInteger t, int rconCounter) { public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
String rBytes = t.toString(16); StringBuilder rBytes = new StringBuilder(t.toString(16));
// Add zero padding // Add zero padding
while (rBytes.length() < 8) { while (rBytes.length() < 8) {
rBytes = "0" + rBytes; rBytes.insert(0, "0");
} }
// rotate the first 16 bits to the back // rotate the first 16 bits to the back
String rotatingBytes = rBytes.substring(0, 2); String rotatingBytes = rBytes.substring(0, 2);
String fixedBytes = rBytes.substring(2); String fixedBytes = rBytes.substring(2);
rBytes = fixedBytes + rotatingBytes; rBytes = new StringBuilder(fixedBytes + rotatingBytes);
// apply S-Box to all 8-Bit Substrings // apply S-Box to all 8-Bit Substrings
for (int i = 0; i < 4; i++) { 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]; currentByte = SBOX[currentByte];
// add the current RCON value to the first byte // add the current RCON value to the first byte
@ -246,27 +242,26 @@ public class AES {
currentByte = currentByte ^ RCON[rconCounter]; currentByte = currentByte ^ RCON[rconCounter];
} }
currentByteBits = Integer.toHexString(currentByte); currentByteBits = new StringBuilder(Integer.toHexString(currentByte));
// Add zero padding // Add zero padding
while (currentByteBits.length() < 2) { while (currentByteBits.length() < 2) {
currentByteBits = '0' + currentByteBits; currentByteBits.insert(0, '0');
} }
// replace bytes in original string // 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); // t = new BigInteger(rBytes, 16);
// return t; // 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 * 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 * @return array of 10 + 1 round keys
*/ */
public static BigInteger[] keyExpansion(BigInteger initialKey) { public static BigInteger[] keyExpansion(BigInteger initialKey) {
@ -332,11 +327,11 @@ public class AES {
public static int[] splitBlockIntoCells(BigInteger block) { public static int[] splitBlockIntoCells(BigInteger block) {
int[] cells = new int[16]; 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 // Append leading 0 for full "128-bit" string
while (blockBits.length() < 128) { while (blockBits.length() < 128) {
blockBits = '0' + blockBits; blockBits.insert(0, '0');
} }
// split 128 to 8 bit cells // split 128 to 8 bit cells
@ -356,24 +351,22 @@ public class AES {
*/ */
public static BigInteger mergeCellsIntoBlock(int[] cells) { public static BigInteger mergeCellsIntoBlock(int[] cells) {
String blockBits = ""; StringBuilder blockBits = new StringBuilder();
for (int i = 0; i < 16; i++) { 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 // Append leading 0 for full "8-bit" strings
while (cellBits.length() < 8) { 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 * @return ciphertext XOR key
*/ */
public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger 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. * substitutes 8-Bit long substrings of the input using the S-Box and returns the result.
* *
* @param ciphertext
* @return subtraction Output * @return subtraction Output
*/ */
public static BigInteger subBytes(BigInteger ciphertext) { 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 * substitutes 8-Bit long substrings of the input using the inverse S-Box for decryption and
* returns the result. * returns the result.
* *
* @param ciphertext
* @return subtraction Output * @return subtraction Output
*/ */
public static BigInteger subBytesDec(BigInteger ciphertext) { 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. * Cell permutation step. Shifts cells within the rows of the input and returns the result.
*
* @param ciphertext
*/ */
public static BigInteger shiftRows(BigInteger ciphertext) { public static BigInteger shiftRows(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(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 * Cell permutation step for decryption . Shifts cells within the rows of the input and returns
* the result. * the result.
*
* @param ciphertext
*/ */
public static BigInteger shiftRowsDec(BigInteger ciphertext) { public static BigInteger shiftRowsDec(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext); int[] cells = splitBlockIntoCells(ciphertext);
@ -490,8 +477,6 @@ public class AES {
/** /**
* Applies the Rijndael MixColumns to the input and returns the result. * Applies the Rijndael MixColumns to the input and returns the result.
*
* @param ciphertext
*/ */
public static BigInteger mixColumns(BigInteger 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. * Applies the inverse Rijndael MixColumns for decryption to the input and returns the result.
*
* @param ciphertext
*/ */
public static BigInteger mixColumnsDec(BigInteger ciphertext) { public static BigInteger mixColumnsDec(BigInteger ciphertext) {
@ -563,7 +546,6 @@ public class AES {
* Decrypts the ciphertext with the key and returns the result * Decrypts the ciphertext with the key and returns the result
* *
* @param cipherText The Encrypted text which we want to decrypt * @param cipherText The Encrypted text which we want to decrypt
* @param key
* @return decryptedText * @return decryptedText
*/ */
public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { public static BigInteger decrypt(BigInteger cipherText, BigInteger key) {
@ -596,8 +578,7 @@ public class AES {
char choice = input.nextLine().charAt(0); char choice = input.nextLine().charAt(0);
String in; String in;
switch (choice) { switch (choice) {
case 'E': case 'E', 'e' -> {
case 'e':
System.out.println("Choose a plaintext block (128-Bit Integer in base 16):"); System.out.println("Choose a plaintext block (128-Bit Integer in base 16):");
in = input.nextLine(); in = input.nextLine();
BigInteger plaintext = new BigInteger(in, 16); BigInteger plaintext = new BigInteger(in, 16);
@ -606,9 +587,8 @@ public class AES {
BigInteger encryptionKey = new BigInteger(in, 16); BigInteger encryptionKey = new BigInteger(in, 16);
System.out.println( System.out.println(
"The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16)); "The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16));
break; }
case 'D': case 'D', 'd' -> {
case 'd':
System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):"); System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):");
in = input.nextLine(); in = input.nextLine();
BigInteger ciphertext = new BigInteger(in, 16); BigInteger ciphertext = new BigInteger(in, 16);
@ -617,9 +597,8 @@ public class AES {
BigInteger decryptionKey = new BigInteger(in, 16); BigInteger decryptionKey = new BigInteger(in, 16);
System.out.println( System.out.println(
"The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16)); "The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16));
break; }
default: default -> System.out.println("** End **");
System.out.println("** End **");
} }
} }
} }

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -42,15 +42,12 @@ public class AESEncryption {
public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(128); // The AES key size in number of bits aesKeyGenerator.init(128); // The AES key size in number of bits
SecretKey secKey = aesKeyGenerator.generateKey(); return aesKeyGenerator.generateKey();
return secKey;
} }
/** /**
* Encrypts plainText in AES using the secret key * Encrypts plainText in AES using the secret key
* *
* @param plainText
* @param secKey
* @return byteCipherText (The encrypted text) * @return byteCipherText (The encrypted text)
* @throws NoSuchPaddingException (from Cipher) * @throws NoSuchPaddingException (from Cipher)
* @throws NoSuchAlgorithmException (from Cipher) * @throws NoSuchAlgorithmException (from Cipher)
@ -64,21 +61,13 @@ public class AESEncryption {
// AES defaults to AES/ECB/PKCS5Padding in Java 7 // AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES"); Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey); aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes()); return aesCipher.doFinal(plainText.getBytes());
return byteCipherText;
} }
/** /**
* Decrypts encrypted byte array using the key used for encryption. * Decrypts encrypted byte array using the key used for encryption.
* *
* @param byteCipherText
* @param secKey
* @return plainText * @return plainText
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/ */
public static String decryptText(byte[] byteCipherText, SecretKey secKey) public static String decryptText(byte[] byteCipherText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, 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 * 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 * this is faster regarding other solution is using StringBuilder
* https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338}
* *
* @param hash (in binary)
* @return hexHash * @return hexHash
*/ */
public static String bytesToHex(byte[] bytes) { public static String bytesToHex(byte[] bytes) {

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
import java.util.Scanner; 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 * Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B
* *
* @param message
* @param shift
* @return Encrypted message * @return Encrypted message
*/ */
public static String encode(String message, int shift) { public static String encode(String message, int shift) {
String encoded = ""; StringBuilder encoded = new StringBuilder();
shift %= 26; shift %= 26;
@ -33,29 +31,27 @@ public class Caesar {
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current += shift; 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)) { } else if (IsSmallLatinLetter(current)) {
current += shift; 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 { } 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 * Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A
* *
* @param encryptedMessage
* @param shift
* @return message * @return message
*/ */
public static String decode(String encryptedMessage, int shift) { public static String decode(String encryptedMessage, int shift) {
String decoded = ""; StringBuilder decoded = new StringBuilder();
shift %= 26; shift %= 26;
@ -65,22 +61,21 @@ public class Caesar {
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current -= shift; 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)) { } else if (IsSmallLatinLetter(current)) {
current -= shift; 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 { } 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 * @return true if character is capital Latin letter or false for others
*/ */
private static boolean IsCapitalLatinLetter(char c) { 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 * @return true if character is small Latin letter or false for others
*/ */
private static boolean IsSmallLatinLetter(char c) { private static boolean IsSmallLatinLetter(char c) {

View File

@ -1,4 +1,6 @@
package ciphers; package Ciphers;
import java.util.Objects;
/** /**
* Columnar Transposition Cipher Encryption and Decryption. * Columnar Transposition Cipher Encryption and Decryption.
@ -27,13 +29,13 @@ public class ColumnarTranspositionCipher {
abecedariumBuilder(500); abecedariumBuilder(500);
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
String wordEncrypted = ""; StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[i].length; i++) { for (int i = 0; i < sortedTable[i].length; i++) {
for (int j = 1; j < sortedTable.length; j++) { 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) { public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.keyword = keyword;
if (abecedarium != null) { ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
ColumnarTranspositionCipher.abecedarium = abecedarium;
} else {
ColumnarTranspositionCipher.abecedarium = ABECEDARIUM;
}
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
String wordEncrypted = ""; StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[0].length; i++) { for (int i = 0; i < sortedTable[0].length; i++) {
for (int j = 1; j < sortedTable.length; j++) { 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 * @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule
*/ */
public static String decrypter() { public static String decrypter() {
String wordDecrypted = ""; StringBuilder wordDecrypted = new StringBuilder();
for (int i = 1; i < table.length; i++) { for (int i = 1; i < table.length; i++) {
for (Object item : table[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 * @return tableSorted
*/ */
private static Object[][] sortTable(Object[][] table) { private static Object[][] sortTable(Object[][] table) {
@ -147,9 +144,6 @@ public class ColumnarTranspositionCipher {
} }
/** /**
* @param table
* @param rows
* @param column
* @return columnArray * @return columnArray
*/ */
private static Object[] getColumn(Object[][] table, int rows, int column) { private static Object[] getColumn(Object[][] table, int rows, int column) {
@ -160,12 +154,6 @@ public class ColumnarTranspositionCipher {
return columnArray; return columnArray;
} }
/**
* @param table
* @param firstColumnIndex
* @param secondColumnIndex
* @param columnToSwitch
*/
private static void switchColumns( private static void switchColumns(
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
for (int i = 0; i < table.length; i++) { 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 * @param value Number of characters being used based on the ASCII Table
*/ */
private static void abecedariumBuilder(int value) { private static void abecedariumBuilder(int value) {
abecedarium = ""; StringBuilder t = new StringBuilder();
for (int i = 0; i < value; i++) { for (int i = 0; i < value; i++) {
abecedarium += (char) i; t.append((char) i);
} }
abecedarium = t.toString();
} }
private static void showTable() { private static void showTable() {

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
@ -20,13 +20,11 @@ public final class RSA {
private BigInteger modulus, privateKey, publicKey; private BigInteger modulus, privateKey, publicKey;
/** @param bits */
public RSA(int bits) { public RSA(int bits) {
generateKeys(bits); generateKeys(bits);
} }
/** /**
* @param message
* @return encrypted message * @return encrypted message
*/ */
public synchronized String encrypt(String message) { public synchronized String encrypt(String message) {
@ -34,7 +32,6 @@ public final class RSA {
} }
/** /**
* @param message
* @return encrypted message as big integer * @return encrypted message as big integer
*/ */
public synchronized BigInteger encrypt(BigInteger message) { public synchronized BigInteger encrypt(BigInteger message) {
@ -42,7 +39,6 @@ public final class RSA {
} }
/** /**
* @param encryptedMessage
* @return plain message * @return plain message
*/ */
public synchronized String decrypt(String encryptedMessage) { public synchronized String decrypt(String encryptedMessage) {
@ -50,7 +46,6 @@ public final class RSA {
} }
/** /**
* @param encryptedMessage
* @return plain message as big integer * @return plain message as big integer
*/ */
public synchronized BigInteger decrypt(BigInteger encryptedMessage) { public synchronized BigInteger decrypt(BigInteger encryptedMessage) {
@ -59,8 +54,6 @@ public final class RSA {
/** /**
* Generate a new public and private key set. * Generate a new public and private key set.
*
* @param bits
*/ */
public synchronized void generateKeys(int bits) { public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom(); SecureRandom r = new SecureRandom();

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
import java.util.*; import java.util.*;
@ -16,15 +16,13 @@ public class SimpleSubstitutionCipher {
/** /**
* Encrypt text by replacing each element with its opposite character. * Encrypt text by replacing each element with its opposite character.
* *
* @param message
* @param cipherSmall
* @return Encrypted message * @return Encrypted message
*/ */
public static String encode(String message, String cipherSmall) { public static String encode(String message, String cipherSmall) {
String encoded = ""; StringBuilder encoded = new StringBuilder();
// This map is used to encode // This map is used to encode
Map<Character, Character> cipherMap = new HashMap<Character, Character>(); Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a'; char beginSmallLetter = 'a';
char beginCapitalLetter = 'A'; char beginCapitalLetter = 'A';
@ -39,24 +37,22 @@ public class SimpleSubstitutionCipher {
} }
for (int i = 0; i < message.length(); i++) { for (int i = 0; i < message.length(); i++) {
if (Character.isAlphabetic(message.charAt(i))) encoded += cipherMap.get(message.charAt(i)); if (Character.isAlphabetic(message.charAt(i))) encoded.append(cipherMap.get(message.charAt(i)));
else encoded += 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. * Decrypt message by replacing each element with its opposite character in cipher.
* *
* @param encryptedMessage
* @param cipherSmall
* @return message * @return message
*/ */
public static String decode(String encryptedMessage, String cipherSmall) { public static String decode(String encryptedMessage, String cipherSmall) {
String decoded = ""; StringBuilder decoded = new StringBuilder();
Map<Character, Character> cipherMap = new HashMap<Character, Character>(); Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a'; char beginSmallLetter = 'a';
char beginCapitalLetter = 'A'; char beginCapitalLetter = 'A';
@ -71,11 +67,11 @@ public class SimpleSubstitutionCipher {
for (int i = 0; i < encryptedMessage.length(); i++) { for (int i = 0; i < encryptedMessage.length(); i++) {
if (Character.isAlphabetic(encryptedMessage.charAt(i))) if (Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded += cipherMap.get(encryptedMessage.charAt(i)); decoded.append(cipherMap.get(encryptedMessage.charAt(i)));
else decoded += encryptedMessage.charAt(i); else decoded.append(encryptedMessage.charAt(i));
} }
return decoded; return decoded.toString();
} }
/** TODO remove main and make JUnit Testing */ /** TODO remove main and make JUnit Testing */

View File

@ -1,4 +1,4 @@
package ciphers; package Ciphers;
/** /**
* A Java implementation of Vigenere Cipher. * A Java implementation of Vigenere Cipher.

View File

@ -1,68 +0,0 @@
package Misc;
import java.util.Scanner;
/**
*
<h1>Find the Transpose of Matrix!</h1>
Simply take input from the user and
* print the matrix before the transpose and after the transpose.
*
<p>
* <b>Note:</b> 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");
}
}
}

View File

@ -1,5 +1,5 @@
## ciphers ## Ciphers
* [AES](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AES.java) * [AES](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AES.java)
* [AESEncryption](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AESEncryption.java) * [AESEncryption](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AESEncryption.java)
* [Caesar](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Caesar.java) * [Caesar](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Caesar.java)
@ -96,7 +96,7 @@
* [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/TrieImp.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) * [ValidBSTOrNot](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/ValidBSTOrNot.java)
## divideconquer ## DivideAndConquer
* [ClosestPair](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/ClosestPair.java) * [ClosestPair](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/ClosestPair.java)
* [SkylineAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/SkylineAlgorithm.java) * [SkylineAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/SkylineAlgorithm.java)
@ -274,7 +274,7 @@
* [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java) * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java)
* [TimSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/TimSort.java) * [TimSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/TimSort.java)
## strings ## Strings
* [Alphabetical](https://github.com/TheAlgorithms/Java/blob/master/strings/Alphabetical.java) * [Alphabetical](https://github.com/TheAlgorithms/Java/blob/master/strings/Alphabetical.java)
* [CharactersSame](https://github.com/TheAlgorithms/Java/blob/master/strings/CharactersSame.java) * [CharactersSame](https://github.com/TheAlgorithms/Java/blob/master/strings/CharactersSame.java)
* [CheckAnagrams](https://github.com/TheAlgorithms/Java/blob/master/strings/CheckAnagrams.java) * [CheckAnagrams](https://github.com/TheAlgorithms/Java/blob/master/strings/CheckAnagrams.java)

View File

@ -2,32 +2,33 @@
Time Complexity = O(E), where E is equal to the number of edges 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.*; import java.util.*;
public class A_Star { public class A_Star {
private static class Graph { private static class Graph {
// Graph's structure can be changed only applying changes to this class. // Graph's structure can be changed only applying changes to this class.
private ArrayList<Edge>[] graph; private ArrayList<ArrayList<Edge>> graph;
// Initialise ArrayLists in Constructor // Initialise ArrayLists in Constructor
public Graph(int size) { public Graph(int size) {
this.graph = new ArrayList[size]; this.graph = new ArrayList<>();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
this.graph[i] = new ArrayList<>(); this.graph.set(i, new ArrayList<>());
} }
} }
private ArrayList<Edge> getNeighbours(int from) { private ArrayList<Edge> 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. // Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) { private void addEdge(Edge edge) {
this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); this.graph.get(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.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
} }
} }
@ -83,7 +84,7 @@ public class A_Star {
private void printSolution() { private void printSolution() {
if (this.path != null) if (this.path != null)
System.out.println( 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"); else System.out.println("There is no path available to connect the points");
} }
} }
@ -150,7 +151,7 @@ public class A_Star {
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 // 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; boolean solutionFound = false;
PathAndDistance currentData = new PathAndDistance(-1, null, -1); PathAndDistance currentData = new PathAndDistance(-1, null, -1);

View File

@ -22,7 +22,7 @@ public class DecimalToAnyUsingStack {
private static String convert(int number, int radix) { private static String convert(int number, int radix) {
if (radix < 2 || radix > 16) { if (radix < 2 || radix > 16) {
throw new ArithmeticException( throw new ArithmeticException(
String.format("Invalid input -> number:%d,radius:%d", number, radix)); Strings.format("Invalid input -> number:%d,radius:%d", number, radix));
} }
char[] tables = { char[] tables = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

View File

@ -82,7 +82,7 @@ public class AVLTree {
System.out.println(this.root.height); System.out.println(this.root.height);
} }
private void display (Node node) { private void display (Node node) {
String str=""; Strings str="";
if(node.left!=null) if(node.left!=null)
str+=node.left.data+"=>"; str+=node.left.data+"=>";
else else

View File

@ -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 * For a set of points in a coordinates system (10000 maximum), ClosestPair class calculates the two
* closest points. * closest points.
*
* @author: anonymous
* @author: Marisa Afuera
*/ */
public final class ClosestPair { public final class ClosestPair {
/** Number of points */ /** Number of points */
int numberPoints = 0; int numberPoints;
/** Input data, maximum 10000. */ /** Input data, maximum 10000. */
private Location[] array; private Location[] array;
/** Minimum point coordinate. */ /** Minimum point coordinate. */
@ -40,8 +39,8 @@ public final class ClosestPair {
/** Location class is an auxiliary type to keep points coordinates. */ /** Location class is an auxiliary type to keep points coordinates. */
public static class Location { public static class Location {
double x = 0; double x;
double y = 0; double y;
/** /**
* @param xpar (IN Parameter) x coordinate <br> * @param xpar (IN Parameter) x coordinate <br>
@ -172,9 +171,9 @@ public final class ClosestPair {
// divide-right array // divide-right array
System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX);
double minLeftArea = 0; // Minimum length of left array double minLeftArea; // Minimum length of left array
double minRightArea = 0; // Minimum length of right array double minRightArea; // Minimum length of right array
double minValue = 0; // Minimum lengt double minValue; // Minimum lengt
minLeftArea = closestPair(leftArray, divideX); // recursive closestPair minLeftArea = closestPair(leftArray, divideX); // recursive closestPair
minRightArea = closestPair(rightArray, indexNum - divideX); minRightArea = closestPair(rightArray, indexNum - divideX);
@ -209,7 +208,7 @@ public final class ClosestPair {
} }
yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates
/* Coordinates in Window */ /* Coordinates in Window */
double length = 0; double length;
// size comparison within window // size comparison within window
for (int i = 0; i < secondCount - 1; i++) { for (int i = 0; i < secondCount - 1; i++) {
for (int j = (i + 1); j < secondCount; j++) { for (int j = (i + 1); j < secondCount; j++) {
@ -246,9 +245,9 @@ public final class ClosestPair {
public double bruteForce(final Location[] arrayParam) { public double bruteForce(final Location[] arrayParam) {
double minValue = Double.MAX_VALUE; // minimum distance double minValue = Double.MAX_VALUE; // minimum distance
double length = 0; double length;
double xGap = 0; // Difference between x coordinates double xGap; // Difference between x coordinates
double yGap = 0; // Difference between y coordinates double yGap; // Difference between y coordinates
double result = 0; double result = 0;
if (arrayParam.length == 2) { if (arrayParam.length == 2) {
@ -297,7 +296,6 @@ public final class ClosestPair {
* main function: execute class. * main function: execute class.
* *
* @param args (IN Parameter) <br> * @param args (IN Parameter) <br>
* @throws IOException If an input or output exception occurred
*/ */
public static void main(final String[] args) { public static void main(final String[] args) {

View File

@ -1,4 +1,4 @@
package divideconquer; package DivideAndConquer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;

View File

@ -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.
*
* <p>Find the sum of all the multiples of 3 or 5 below 1000.
*
* <p>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;
}
}

View File

@ -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:
*
* <p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*
* <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*
* <p>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;
}
}

View File

@ -1,62 +0,0 @@
package ProjectEuler;
/**
* The prime factors of 13195 are 5, 7, 13 and 29.
*
* <p>What is the largest prime factor of the number 600851475143 ?
*
* <p>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;
}
}

View File

@ -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.
*
* <p>Find the largest palindrome made from the product of two 3-digit numbers.
*
* <p>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 */
}
}

View File

@ -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.
*
* <p>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;
}
}

View File

@ -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.
*
* <p>What is the 10 001st prime number?
*
* <p>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;
}
}

View File

@ -1,28 +0,0 @@
package ProjectEuler;
/**
* A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
*
* <p>a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
*
* <p>There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
*
* <p>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 */
}
}

View File

@ -1,55 +0,0 @@
package ProjectEuler;
/**
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
*
* <p>Find the sum of all the primes below two million.
*
* <p>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;
}
}

View File

@ -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:
*
* <p>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
*
* <p>Let us list the factors of the first seven triangle numbers:
*
* <p>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.
*
* <p>What is the value of the first triangle number to have over five hundred divisors?
*
* <p>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;
}
}

View File

@ -158,24 +158,24 @@ From [Wikipedia][binary-wiki]: 이진 탐색, (also known as half-interval searc
| 전환 | 다이나믹프로그래밍(DP) | 암호 | 그 외 것들 | | 전환 | 다이나믹프로그래밍(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 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](Dynamic%20Programming/EggDropping.java) | [Columnar Transposition Cipher](ciphers/ColumnarTranspositionCipher.java) | [Palindromic Prime Checker](misc/PalindromicPrime.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](Dynamic%20Programming/Fibonacci.java) | [RSA](ciphers/RSA.java) | More soon... | | [Binary to Decimal](Conversions/BinaryToDecimal.java) | [Fibonacci](DynamicProgramming/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 HexaDecimal](Conversions/BinaryToHexadecimal.java) | [Kadane Algorithm](DynamicProgramming/KadaneAlgorithm.java) | more coming soon... |
| [Binary to Octal](Conversions/BinaryToOctal.java) | [Knapsack](Dynamic%20Programming/Knapsack.java) | | [Binary to Octal](Conversions/BinaryToOctal.java) | [Knapsack](DynamicProgramming/Knapsack.java) |
| [Decimal To Any Base](Conversions/DecimalToAnyBase.java) | [Longest Common Subsequence](Dynamic%20Programming/LongestCommonSubsequence.java) | | [Decimal To Any Base](Conversions/DecimalToAnyBase.java) | [Longest Common Subsequence](DynamicProgramming/LongestCommonSubsequence.java) |
| [Decimal To Binary](Conversions/DecimalToBinary.java) | [Longest Increasing Subsequence](Dynamic%20Programming/LongestIncreasingSubsequence.java) | | [Decimal To Binary](Conversions/DecimalToBinary.java) | [Longest Increasing Subsequence](DynamicProgramming/LongestIncreasingSubsequence.java) |
| [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java) | [Rod Cutting](Dynamic%20Programming/RodCutting.java) | | [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java) | [Rod Cutting](DynamicProgramming/RodCutting.java) |
| and much more... | and more... | | and much more... | and more... |
### 자료 구조 ### 자료 구조
| 그래프 | 힙 | 리스트 | 큐 | | 그래프 | 힙 | 리스트 | 큐 |
| ----------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- | | ----------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------- |
| [너비우선탐색](DataStructures/Graphs/BFS.java) | [빈 힙 예외처리](DataStructures/Heaps/EmptyHeapException.java) | [원형 연결리스트](DataStructures/Lists/CircleLinkedList.java) | [제너릭 어레이 리스트 큐](DataStructures/Queues/GenericArrayListQueue.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/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/Graphs.java) | [힙 요소](DataStructures/Heaps/HeapElement.java) | [단순 연결리스트](DataStructures/Lists/SinglyLinkedList.java) |
| [크루스칼 알고리즘](DataStructures/Graphs/KruskalsAlgorithm.java) | [최대힙](Data%Structures/Heaps/MaxHeap.java) | | [크루스칼 알고리즘](DataStructures/Graphs/Kruskal.java) | [최대힙](DataStructures/Heaps/MaxHeap.java) |
| [행렬 그래프](DataStructures/Graphs/MatrixGraphs.java) | [최소힙](DataStructures/Heaps/MinHeap.java) | | [행렬 그래프](DataStructures/Graphs/MatrixGraphs.java) | [최소힙](DataStructures/Heaps/MinHeap.java) |
| [프림 최소신장트리](DataStructures/Graphs/PrimMST.java) | | [프림 최소신장트리](DataStructures/Graphs/PrimMST.java) |
@ -187,5 +187,5 @@ From [Wikipedia][binary-wiki]: 이진 탐색, (also known as half-interval searc
- [Bags](DataStructures/Bags/Bag.java) - [Bags](DataStructures/Bags/Bag.java)
- [Buffer](DataStructures/Buffers/CircularBuffer.java) - [Buffer](DataStructures/Buffers/CircularBuffer.java)
- [HashMap](DataStructures/HashMap/HashMap.java) - [HashMap](DataStructures/HashMap/Hashing/HashMap.java)
- [Matrix](DataStructures/Matrix/Matrix.java) -

View File

@ -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.

View File

@ -1,3 +1,5 @@
package Searches;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -12,21 +14,21 @@ public class IterativeBinarySearch_Test {
@Test @Test
void tc1_key_khong_co_trong_mang() { void tc1_key_khong_co_trong_mang() {
assertTrue(search.find(arr, 11) == -1); assertEquals(-1, search.find(arr, 11));
} }
@Test @Test
void tc2_key_nam_chinh_giua_mang() { void tc2_key_nam_chinh_giua_mang() {
assertTrue(search.find(arr, 5) == 5); assertEquals(5, search.find(arr, 5));
} }
@Test @Test
void tc3_key_nam_cuoi_mang() { void tc3_key_nam_cuoi_mang() {
assertTrue(search.find(arr, 10) == 10); assertEquals(10, search.find(arr, 10));
} }
@Test @Test
void tc4_key_nam_dau_mang() { void tc4_key_nam_dau_mang() {
assertTrue(search.find(arr, 0) == 0); assertEquals(0, search.find(arr, 0));
} }
} }

View File

@ -1,4 +1,4 @@
package strings; package Strings;
/** /**
* Alphabetical order is a system whereby character strings are placed in order based on the * Alphabetical order is a system whereby character strings are placed in order based on the

View File

@ -1,4 +1,4 @@
package strings; package Strings;
public class CharactersSame { public class CharactersSame {

View File

@ -1,4 +1,4 @@
package strings; package Strings;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;

View File

@ -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 * 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 * @param input a string prints the count of vowels
*/ */
public static void countVowels(String input) { public static void countVowels(String input) {
input.toLowerCase(); input = input.toLowerCase();
int count = 0; int count = 0;
int i = 0; int i = 0;
while (i < input.length()) { while (i < input.length()) {

View File

@ -1,4 +1,4 @@
package strings; package Strings;
import java.util.HashMap; import java.util.HashMap;

View File

@ -1,4 +1,4 @@
package strings; package Strings;
public class Lower { public class Lower {

View File

@ -1,4 +1,4 @@
package strings; package Strings;
/** Wikipedia: https://en.wikipedia.org/wiki/Palindrome */ /** Wikipedia: https://en.wikipedia.org/wiki/Palindrome */
class Palindrome { class Palindrome {

View File

@ -1,4 +1,4 @@
package strings; package Strings;
/** Wikipedia: https://en.wikipedia.org/wiki/Pangram */ /** Wikipedia: https://en.wikipedia.org/wiki/Pangram */
public class Pangram { public class Pangram {

View File

@ -1,4 +1,4 @@
package strings; package Strings;
/** Reverse String using different version */ /** Reverse String using different version */
public class ReverseString { public class ReverseString {

View File

@ -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 * Given a string, moving several characters in front of the string to the end of the string. For

View File

@ -1,4 +1,4 @@
package strings; package Strings;
public class Upper { public class Upper {