diff --git a/Zutil.iml b/Zutil.iml
index 5454eb9..a2bde11 100755
--- a/Zutil.iml
+++ b/Zutil.iml
@@ -45,15 +45,5 @@
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/zutil/Encrypter.java b/src/zutil/Encrypter.java
index aa02e94..3ddce27 100644
--- a/src/zutil/Encrypter.java
+++ b/src/zutil/Encrypter.java
@@ -40,203 +40,203 @@ import java.util.Random;
* Basic symmetric encryption example
*/
public class Encrypter {
- // Choices are available at: http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html
- public enum Algorithm {
- /** Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits. **/
- AES,
- /** The AES key wrapping algorithm as described in RFC 3394. **/
- AESWrap,
- /** A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt. **/
- ARCFOUR,
- /** The Blowfish block cipher designed by Bruce Schneier. **/
- Blowfish,
- /** Counter/CBC Mode, as defined in NIST Special Publication SP 800-38C. **/
- CCM,
- /** The Digital Encryption Standard as described in FIPS PUB 46-3. **/
- DES,
- /** Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey. **/
- DESede,
- /** The DESede key wrapping algorithm as described in RFC 3217 . **/
- DESedeWrap,
- /** Elliptic Curve Integrated Encryption Scheme **/
- ECIES,
- /** Galois/Counter Mode, as defined in NIST Special Publication SP 800-38D. **/
- GCM,
- /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/
- RC2,
- /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.) **/
- RC4,
- /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/
- RC5,
- /** The RSA encryption algorithm as defined in PKCS #1 **/
- RSA
- }
- public enum Digest {
- MD2,
- MD5,
- SHA1,
- SHA256,
- SHA384,
- SHA512,
- HmacMD5,
- HmacSHA1,
- HmacSHA256,
- HmacSHA384,
- HmacSHA512
- }
+ // Choices are available at: http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html
+ public enum Algorithm {
+ /** Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits. **/
+ AES,
+ /** The AES key wrapping algorithm as described in RFC 3394. **/
+ AESWrap,
+ /** A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt. **/
+ ARCFOUR,
+ /** The Blowfish block cipher designed by Bruce Schneier. **/
+ Blowfish,
+ /** Counter/CBC Mode, as defined in NIST Special Publication SP 800-38C. **/
+ CCM,
+ /** The Digital Encryption Standard as described in FIPS PUB 46-3. **/
+ DES,
+ /** Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey. **/
+ DESede,
+ /** The DESede key wrapping algorithm as described in RFC 3217 . **/
+ DESedeWrap,
+ /** Elliptic Curve Integrated Encryption Scheme **/
+ ECIES,
+ /** Galois/Counter Mode, as defined in NIST Special Publication SP 800-38D. **/
+ GCM,
+ /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/
+ RC2,
+ /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.) **/
+ RC4,
+ /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/
+ RC5,
+ /** The RSA encryption algorithm as defined in PKCS #1 **/
+ RSA
+ }
+ public enum Digest {
+ MD2,
+ MD5,
+ SHA1,
+ SHA256,
+ SHA384,
+ SHA512,
+ HmacMD5,
+ HmacSHA1,
+ HmacSHA256,
+ HmacSHA384,
+ HmacSHA512
+ }
- // 8-byte Salt
- public static byte[] salt = {
- (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
- (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
- };
+ // 8-byte Salt
+ public static byte[] salt = {
+ (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
+ (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
+ };
- private Cipher encipher;
- private Cipher decipher;
- private Key key;
- private AlgorithmParameterSpec paramSpec;
+ private Cipher encipher;
+ private Cipher decipher;
+ private Key key;
+ private AlgorithmParameterSpec paramSpec;
- /**
- * Generates a random key
- * @param crypto is algorithm to encrypt/decrypt with
- */
- public Encrypter(Algorithm crypto) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{
- KeyGenerator keygenerator = KeyGenerator.getInstance(crypto.toString());
+ /**
+ * Generates a random key
+ * @param crypto is algorithm to encrypt/decrypt with
+ */
+ public Encrypter(Algorithm crypto) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{
+ KeyGenerator keygenerator = KeyGenerator.getInstance(crypto.toString());
- key = keygenerator.generateKey();
- encipher = Cipher.getInstance(key.getAlgorithm());
- decipher = Cipher.getInstance(key.getAlgorithm());
- encipher.init(Cipher.ENCRYPT_MODE, key);
- decipher.init(Cipher.DECRYPT_MODE, key);
- }
+ key = keygenerator.generateKey();
+ encipher = Cipher.getInstance(key.getAlgorithm());
+ decipher = Cipher.getInstance(key.getAlgorithm());
+ encipher.init(Cipher.ENCRYPT_MODE, key);
+ decipher.init(Cipher.DECRYPT_MODE, key);
+ }
- /**
- * Uses the given key for encryption
- * @param key is an existing key to use for encrypting/decrypting
- */
- public Encrypter(Key key) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{
- this.key = key;
- encipher = Cipher.getInstance(key.getAlgorithm());
- decipher = Cipher.getInstance(key.getAlgorithm());
- encipher.init(Cipher.ENCRYPT_MODE, key);
- decipher.init(Cipher.DECRYPT_MODE, key);
- }
+ /**
+ * Uses the given key for encryption
+ * @param key is an existing key to use for encrypting/decrypting
+ */
+ public Encrypter(Key key) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{
+ this.key = key;
+ encipher = Cipher.getInstance(key.getAlgorithm());
+ decipher = Cipher.getInstance(key.getAlgorithm());
+ encipher.init(Cipher.ENCRYPT_MODE, key);
+ decipher.init(Cipher.DECRYPT_MODE, key);
+ }
- /**
- * Creates a encrypter with a passphrase.
- *
- * @param stringKey is a passphrase to use as key
- * @param crypto is algorithm to encrypt/decrypt with
- */
- public Encrypter(String stringKey, Algorithm crypto) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException {
- this(stringKey, Digest.HmacSHA1, crypto, 500,
- (crypto==Algorithm.DES ? 64 : 128));
- }
+ /**
+ * Creates a encrypter with a passphrase.
+ *
+ * @param stringKey is a passphrase to use as key
+ * @param crypto is algorithm to encrypt/decrypt with
+ */
+ public Encrypter(String stringKey, Algorithm crypto) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException {
+ this(stringKey, Digest.HmacSHA1, crypto, 500,
+ (crypto==Algorithm.DES ? 64 : 128));
+ }
- public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException {
- // Install SunJCE provider
- Provider sunJce = new com.sun.crypto.provider.SunJCE();
- Security.addProvider(sunJce);
+ public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException {
+ // Install SunJCE provider
+ Provider sunJce = new com.sun.crypto.provider.SunJCE();
+ Security.addProvider(sunJce);
- // Generate the secret key specs.
- //String instance = "PBEWith"+ digest +"And"+ crypto;
- String instance = "PBKDF2With"+ digest;
- SecretKeyFactory factory = SecretKeyFactory.getInstance(instance);
- KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize);
- SecretKey tmp = factory.generateSecret(keySpec);
- key = new SecretKeySpec(tmp.getEncoded(), crypto.toString());
- //key = new SecretKeySpec(stringKey.getBytes(), crypto.toString());
+ // Generate the secret key specs.
+ //String instance = "PBEWith"+ digest +"And"+ crypto;
+ String instance = "PBKDF2With"+ digest;
+ SecretKeyFactory factory = SecretKeyFactory.getInstance(instance);
+ KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize);
+ SecretKey tmp = factory.generateSecret(keySpec);
+ key = new SecretKeySpec(tmp.getEncoded(), crypto.toString());
+ //key = new SecretKeySpec(stringKey.getBytes(), crypto.toString());
- encipher = Cipher.getInstance(key.getAlgorithm());
- decipher = Cipher.getInstance(key.getAlgorithm());
- encipher.init(Cipher.ENCRYPT_MODE, key);
- decipher.init(Cipher.DECRYPT_MODE, key);
- }
+ encipher = Cipher.getInstance(key.getAlgorithm());
+ decipher = Cipher.getInstance(key.getAlgorithm());
+ encipher.init(Cipher.ENCRYPT_MODE, key);
+ decipher.init(Cipher.DECRYPT_MODE, key);
+ }
- /**
- * Encrypts the given data
- *
- * @param data is the data to encrypt
- * @return The encrypted data
- */
- public byte[] encrypt(byte[] data){
- try {
- byte[] encryption = new byte[encipher.getOutputSize(data.length)];
- int ctLength = encipher.update(data, 0, data.length, encryption, 0);
+ /**
+ * Encrypts the given data
+ *
+ * @param data is the data to encrypt
+ * @return The encrypted data
+ */
+ public byte[] encrypt(byte[] data){
+ try {
+ byte[] encryption = new byte[encipher.getOutputSize(data.length)];
+ int ctLength = encipher.update(data, 0, data.length, encryption, 0);
- ctLength += encipher.doFinal(encryption, ctLength);
- return encryption;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
+ ctLength += encipher.doFinal(encryption, ctLength);
+ return encryption;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Adds encryption to the OutputStream
- * @param out is the OutputStream to enable encryption on
- * @return A new encrypted OutputStream
- */
- public OutputStream encrypt(OutputStream out) {
- // Bytes written to out will be encrypted
- return new CipherOutputStream(out, encipher);
+ /**
+ * Adds encryption to the OutputStream
+ * @param out is the OutputStream to enable encryption on
+ * @return A new encrypted OutputStream
+ */
+ public OutputStream encrypt(OutputStream out) {
+ // Bytes written to out will be encrypted
+ return new CipherOutputStream(out, encipher);
- }
+ }
- /**
- * Decrypts encrypted data
- * @param encrypted is the encrypted data
- * @return The decrypted data
- */
- public byte[] decrypt(byte[] encrypted){
- try {
- byte[] dataTmp = new byte[encrypted.length];
- int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0);
- ptLength += decipher.doFinal(dataTmp, ptLength);
+ /**
+ * Decrypts encrypted data
+ * @param encrypted is the encrypted data
+ * @return The decrypted data
+ */
+ public byte[] decrypt(byte[] encrypted){
+ try {
+ byte[] dataTmp = new byte[encrypted.length];
+ int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0);
+ ptLength += decipher.doFinal(dataTmp, ptLength);
- byte[] data = new byte[ptLength];
- System.arraycopy(dataTmp, 0, data, 0, ptLength);
- return data;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
+ byte[] data = new byte[ptLength];
+ System.arraycopy(dataTmp, 0, data, 0, ptLength);
+ return data;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Adds decryption to the InputStream
- * @param in is the InputStream to enable decryption on
- * @return A new decrypted InputStream
- */
- public InputStream decrypt(InputStream in) {
- // Bytes read from in will be decrypted
- return new CipherInputStream(in, decipher);
+ /**
+ * Adds decryption to the InputStream
+ * @param in is the InputStream to enable decryption on
+ * @return A new decrypted InputStream
+ */
+ public InputStream decrypt(InputStream in) {
+ // Bytes read from in will be decrypted
+ return new CipherInputStream(in, decipher);
- }
+ }
- /**
- * @return The key for this encrypter
- */
- public Key getKey(){
- return key;
- }
+ /**
+ * @return The key for this encrypter
+ */
+ public Key getKey(){
+ return key;
+ }
- /**
- * @return the algorithm used by this encrypter
- */
- public String getAlgorithm(){
- return key.getAlgorithm();
- }
+ /**
+ * @return the algorithm used by this encrypter
+ */
+ public String getAlgorithm(){
+ return key.getAlgorithm();
+ }
- /**
- * Randomizes the salt for the key
- */
- public static void randomizeSalt(){
- Random random = new Random();
- random.nextBytes(salt);
- }
+ /**
+ * Randomizes the salt for the key
+ */
+ public static void randomizeSalt(){
+ Random random = new Random();
+ random.nextBytes(salt);
+ }
}
diff --git a/src/zutil/Hasher.java b/src/zutil/Hasher.java
index bcf465a..58f577a 100755
--- a/src/zutil/Hasher.java
+++ b/src/zutil/Hasher.java
@@ -37,133 +37,133 @@ import java.security.NoSuchAlgorithmException;
public class Hasher {
- /**
- * Returns a hash of a file
- *
- * @param file is the path to the file
- * @param hashType is the hash type
- * @return a String with the hash
- */
- public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException {
- MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5"
- InputStream is = new FileInputStream(file);
- String output = "";
- byte[] buffer = new byte[8192];
- int read = 0;
- try {
- while( (read = is.read(buffer)) > 0) {
- digest.update(buffer, 0, read);
- }
- byte[] md5sum = digest.digest();
- BigInteger bigInt = new BigInteger(1, md5sum);
- output = bigInt.toString(16);
- }
- catch(IOException e) {
- throw new RuntimeException("Unable to process file for "+hashType+" hash", e);
- }
- is.close();
+ /**
+ * Returns a hash of a file
+ *
+ * @param file is the path to the file
+ * @param hashType is the hash type
+ * @return a String with the hash
+ */
+ public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException {
+ MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5"
+ InputStream is = new FileInputStream(file);
+ String output = "";
+ byte[] buffer = new byte[8192];
+ int read = 0;
+ try {
+ while( (read = is.read(buffer)) > 0) {
+ digest.update(buffer, 0, read);
+ }
+ byte[] md5sum = digest.digest();
+ BigInteger bigInt = new BigInteger(1, md5sum);
+ output = bigInt.toString(16);
+ }
+ catch(IOException e) {
+ throw new RuntimeException("Unable to process file for "+hashType+" hash", e);
+ }
+ is.close();
- return output;
- }
+ return output;
+ }
- /**
- * Returns the MD5 hash of the given object
- *
- * @param str is the String to hash
- * @return an String containing the hash
- */
- public static String MD5(String str){
- try {
- return hash(str, "MD5");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
+ /**
+ * Returns the MD5 hash of the given object
+ *
+ * @param str is the String to hash
+ * @return an String containing the hash
+ */
+ public static String MD5(String str){
+ try {
+ return hash(str, "MD5");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Returns the MD5 hash of the given object
- *
- * @param object is the object to hash
- * @return an String containing the hash
- */
- public static String MD5(Serializable object){
- try {
- return hash(object, "MD5");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Returns the MD5 hash of the given file
- *
- * @param file is the file to hash
- * @return an String containing the hash
- */
- public static String MD5(File file) throws IOException{
- try {
- return hash(file, "MD5");
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- return null;
- }
-
+ /**
+ * Returns the MD5 hash of the given object
+ *
+ * @param object is the object to hash
+ * @return an String containing the hash
+ */
+ public static String MD5(Serializable object){
+ try {
+ return hash(object, "MD5");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- /**
- * Returns the SHA-1 hash of the given object
- *
- * @param str is the String to hash
- * @return an String containing the hash
- */
- public static String SHA1(String str){
- try {
- return hash(str, "SHA-1");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Returns the SHA-1 hash of the given object
- *
- * @param object is the object to hash
- * @return an String containing the hash
- */
- public static String SHA1(Serializable object){
- try {
- return hash(object, "SHA-1");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Returns the SHA-256 hash with a key for the given String
- *
- * @param str is the String to hash
- * @param key is the key to use with the hash
- * @return an String containing the hash
- */
- public static String HMAC_SHA256(String str, String key){
- return HMAC("HmacSHA256", str.getBytes(), key.getBytes());
- }
-
- /**
- * Returns a HMAC hash with a key for the given String
- *
- * @param algo specifies the algorithm to be used
- * @param data is the String to hash
- * @param key is the key to use with the hash
- * @return an String containing the hash
- */
- public static String HMAC(String algo, byte[] data, byte[] key){
- try {
- // Get an hmac_sha1 key from the raw key bytes
+ /**
+ * Returns the MD5 hash of the given file
+ *
+ * @param file is the file to hash
+ * @return an String containing the hash
+ */
+ public static String MD5(File file) throws IOException{
+ try {
+ return hash(file, "MD5");
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+
+ /**
+ * Returns the SHA-1 hash of the given object
+ *
+ * @param str is the String to hash
+ * @return an String containing the hash
+ */
+ public static String SHA1(String str){
+ try {
+ return hash(str, "SHA-1");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * Returns the SHA-1 hash of the given object
+ *
+ * @param object is the object to hash
+ * @return an String containing the hash
+ */
+ public static String SHA1(Serializable object){
+ try {
+ return hash(object, "SHA-1");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * Returns the SHA-256 hash with a key for the given String
+ *
+ * @param str is the String to hash
+ * @param key is the key to use with the hash
+ * @return an String containing the hash
+ */
+ public static String HMAC_SHA256(String str, String key){
+ return HMAC("HmacSHA256", str.getBytes(), key.getBytes());
+ }
+
+ /**
+ * Returns a HMAC hash with a key for the given String
+ *
+ * @param algo specifies the algorithm to be used
+ * @param data is the String to hash
+ * @param key is the key to use with the hash
+ * @return an String containing the hash
+ */
+ public static String HMAC(String algo, byte[] data, byte[] key){
+ try {
+ // Get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key, algo);
// Get a MAC instance and initialize with the signing key
@@ -174,11 +174,11 @@ public class Hasher {
byte[] raw = mac.doFinal( data );
return Converter.toHexString(raw);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
public static String PBKDF2(String data, String salt, int iterations){
try {
@@ -196,97 +196,97 @@ public class Hasher {
}
return null;
}
-
- /**
- * Hashes the given String as UTF8
- *
- * @param object is the String
- * @param hashType is the hash algorithm (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
- * @return a hex String of the hash
- */
- public static String hash(String object, String hashType) throws Exception {
- return hash(object.getBytes(), hashType);//(new BASE64Encoder()).encode(raw);
- }
-
- /**
- * Returns the hash of the given object
- *
- * @param object is the object to hash
- * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
- * @return an String containing the hash
- */
- public static String hash(Serializable object, String hashType) throws Exception {
- return hash(Converter.toBytes(object), hashType);//(new BASE64Encoder()).encode(raw);
- }
- /**
- * Hashes a given byte array
- *
- * @param data is the byte array to hash
- * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
- * @return an String containing the hash
- * @throws Exception
- */
- public static String hash(byte[] data, String hashType) throws Exception {
- MessageDigest md = null;
- md = MessageDigest.getInstance(hashType); //MD5 || SHA
- md.update(data);
+ /**
+ * Hashes the given String as UTF8
+ *
+ * @param object is the String
+ * @param hashType is the hash algorithm (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
+ * @return a hex String of the hash
+ */
+ public static String hash(String object, String hashType) throws Exception {
+ return hash(object.getBytes(), hashType);//(new BASE64Encoder()).encode(raw);
+ }
- byte raw[] = md.digest();
- return Converter.toHexString(raw);//(new BASE64Encoder()).encode(raw);
- }
+ /**
+ * Returns the hash of the given object
+ *
+ * @param object is the object to hash
+ * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
+ * @return an String containing the hash
+ */
+ public static String hash(Serializable object, String hashType) throws Exception {
+ return hash(Converter.toBytes(object), hashType);//(new BASE64Encoder()).encode(raw);
+ }
- /**
- * MurmurHash2 ported from c++ source
- *
- * @param object is the Key
- * @param seed is the seed
- * @return A MurmurHash of the key
- */
- public static int MurmurHash(Serializable object, int seed) throws Exception{
- byte[] data = Converter.toBytes(object);
- int length = data.length;
+ /**
+ * Hashes a given byte array
+ *
+ * @param data is the byte array to hash
+ * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
+ * @return an String containing the hash
+ * @throws Exception
+ */
+ public static String hash(byte[] data, String hashType) throws Exception {
+ MessageDigest md = null;
+ md = MessageDigest.getInstance(hashType); //MD5 || SHA
+ md.update(data);
- //Constants
- int m = 0x5bd1e995;
- int r = 24;
+ byte raw[] = md.digest();
+ return Converter.toHexString(raw);//(new BASE64Encoder()).encode(raw);
+ }
- // Initialize the hash to a 'random' value
- int h = seed ^ length;
+ /**
+ * MurmurHash2 ported from c++ source
+ *
+ * @param object is the Key
+ * @param seed is the seed
+ * @return A MurmurHash of the key
+ */
+ public static int MurmurHash(Serializable object, int seed) throws Exception{
+ byte[] data = Converter.toBytes(object);
+ int length = data.length;
- int i=0;
- for(; i+4>> r;
- k *= m;
+ // Initialize the hash to a 'random' value
+ int h = seed ^ length;
- h *= m;
- h ^= k;
- }
+ int i=0;
+ for(; i+4>> r;
+ k *= m;
- switch(i){
- case 3: h ^= data[length-3] << 16;
- case 2: h ^= data[length-2] << 8;
- case 1: h ^= data[length-1];
- h *= m;
- }
+ h *= m;
+ h ^= k;
+ }
- h ^= h >>> 13;
- h *= m;
- h ^= h >>> 15;
+ // Handle the last few bytes of the input
+ i = length % 4;
- return h;
- }
+ switch(i){
+ case 3: h ^= data[length-3] << 16;
+ case 2: h ^= data[length-2] << 8;
+ case 1: h ^= data[length-1];
+ h *= m;
+ }
+
+ h ^= h >>> 13;
+ h *= m;
+ h ^= h >>> 15;
+
+ return h;
+ }
}
diff --git a/src/zutil/OneInstance.java b/src/zutil/OneInstance.java
index c848208..7b87bcc 100644
--- a/src/zutil/OneInstance.java
+++ b/src/zutil/OneInstance.java
@@ -32,17 +32,17 @@ package zutil;
*
*/
public interface OneInstance {
- /**
- * Checks if the application is already running
- *
- * @return True if the file is locked else false
- */
- public boolean check();
+ /**
+ * Checks if the application is already running
+ *
+ * @return True if the file is locked else false
+ */
+ public boolean check();
- /**
- * Locks the application so that another one can not run
- *
- * @return False if there are a error else true
- */
- public boolean lockApp();
+ /**
+ * Locks the application so that another one can not run
+ *
+ * @return False if there are a error else true
+ */
+ public boolean lockApp();
}
diff --git a/src/zutil/OneInstanceFile.java b/src/zutil/OneInstanceFile.java
index 446881a..7404d27 100644
--- a/src/zutil/OneInstanceFile.java
+++ b/src/zutil/OneInstanceFile.java
@@ -37,85 +37,85 @@ import java.nio.channels.OverlappingFileLockException;
* @author Ziver Koc
*/
public class OneInstanceFile implements OneInstance{
- private File file;
- private FileChannel channel;
- private FileLock lock;
+ private File file;
+ private FileChannel channel;
+ private FileLock lock;
- /**
- * Creates a OneApp class
- *
- * @param filename The name of the file to be locked
- */
- public OneInstanceFile(String filename){
- this.file = new File(System.getProperty("user.home"), filename);
- }
+ /**
+ * Creates a OneApp class
+ *
+ * @param filename The name of the file to be locked
+ */
+ public OneInstanceFile(String filename){
+ this.file = new File(System.getProperty("user.home"), filename);
+ }
- /**
- * Checks if the file have already bean locked
- *
- * @return True if the file is locked else false
- */
- public boolean check() {
- boolean tmp = lockApp();
- if( tmp ) closeLock();
- return !tmp;
- }
+ /**
+ * Checks if the file have already bean locked
+ *
+ * @return True if the file is locked else false
+ */
+ public boolean check() {
+ boolean tmp = lockApp();
+ if( tmp ) closeLock();
+ return !tmp;
+ }
- /**
- * Locks the file
- *
- * @return False if there are a error else true
- */
- public boolean lockApp() {
- try {
- channel = new RandomAccessFile(file, "rw").getChannel();
+ /**
+ * Locks the file
+ *
+ * @return False if there are a error else true
+ */
+ public boolean lockApp() {
+ try {
+ channel = new RandomAccessFile(file, "rw").getChannel();
- try {
- lock = channel.tryLock();
- }
- catch (OverlappingFileLockException e) {
- // already locked by this application
- return false;
- }
+ try {
+ lock = channel.tryLock();
+ }
+ catch (OverlappingFileLockException e) {
+ // already locked by this application
+ return false;
+ }
- if (lock == null || lock.isShared()) {
- // already locked by another application
- return false;
- }
+ if (lock == null || lock.isShared()) {
+ // already locked by another application
+ return false;
+ }
- Runtime.getRuntime().addShutdownHook(new Thread() {
- // destroy the lock when the JVM is closing
- public void run() {
- closeLock();
- deleteFile();
- }
- });
- return true;
- }
- catch (Exception e) {
- closeLock();
- return false;
- }
- }
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ // destroy the lock when the JVM is closing
+ public void run() {
+ closeLock();
+ deleteFile();
+ }
+ });
+ return true;
+ }
+ catch (Exception e) {
+ closeLock();
+ return false;
+ }
+ }
- private void closeLock() {
- try {
- lock.release();
- channel.close();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
+ private void closeLock() {
+ try {
+ lock.release();
+ channel.close();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
- private void deleteFile() {
- try {
- file.delete();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
+ private void deleteFile() {
+ try {
+ file.delete();
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
diff --git a/src/zutil/OneInstanceNetwork.java b/src/zutil/OneInstanceNetwork.java
index 2b6a9c4..62997e7 100644
--- a/src/zutil/OneInstanceNetwork.java
+++ b/src/zutil/OneInstanceNetwork.java
@@ -37,62 +37,62 @@ import java.net.Socket;
* @author Ziver Koc
*/
public class OneInstanceNetwork extends Thread implements OneInstance{
- private int port;
-
- /**
- * Creates a One App objekt
- *
- * @param port The port to lock
- */
- public OneInstanceNetwork(int port){
- this.port = port;
- }
-
- /**
- * Starts the port lock
- *
- * @return Always true
- */
- public boolean lockApp(){
- this.start();
- return true;
- }
-
- /**
- * he port lock thread
- * should not be cald outside the class
- */
- public void run() {
- ServerSocket serverSocket = null;
- Socket clientSocket = null;
- try {
- // Create the server socket
- serverSocket = new ServerSocket(port, 1);
- while (true) {
- // Wait for a connection
- clientSocket = serverSocket.accept();
- clientSocket.close();
- }
- }
- catch (IOException ioe) {
- MultiPrintStream.out.println("Error in JustOneServer: " + ioe);
- }
- }
+ private int port;
- /**
- * Checks if the port is locked
- *
- * @return True if port is locked else false
- */
- public boolean check() {
- try {
- Socket clientSocket = new Socket("localhost", port);
- MultiPrintStream.out.println("Already running!!!");
- clientSocket.close();
- return true;
- }
- catch (Exception e) {
- return false;
- }
- }
+ /**
+ * Creates a One App objekt
+ *
+ * @param port The port to lock
+ */
+ public OneInstanceNetwork(int port){
+ this.port = port;
+ }
+
+ /**
+ * Starts the port lock
+ *
+ * @return Always true
+ */
+ public boolean lockApp(){
+ this.start();
+ return true;
+ }
+
+ /**
+ * he port lock thread
+ * should not be cald outside the class
+ */
+ public void run() {
+ ServerSocket serverSocket = null;
+ Socket clientSocket = null;
+ try {
+ // Create the server socket
+ serverSocket = new ServerSocket(port, 1);
+ while (true) {
+ // Wait for a connection
+ clientSocket = serverSocket.accept();
+ clientSocket.close();
+ }
+ }
+ catch (IOException ioe) {
+ MultiPrintStream.out.println("Error in JustOneServer: " + ioe);
+ }
+ }
+
+ /**
+ * Checks if the port is locked
+ *
+ * @return True if port is locked else false
+ */
+ public boolean check() {
+ try {
+ Socket clientSocket = new Socket("localhost", port);
+ MultiPrintStream.out.println("Already running!!!");
+ clientSocket.close();
+ return true;
+ }
+ catch (Exception e) {
+ return false;
+ }
+ }
}
diff --git a/src/zutil/ProgressListener.java b/src/zutil/ProgressListener.java
index 633652f..d842d49 100644
--- a/src/zutil/ProgressListener.java
+++ b/src/zutil/ProgressListener.java
@@ -32,13 +32,13 @@ package zutil;
*
*/
public interface ProgressListener {
-
- /**
- * This method is called when the progress is updated
- *
- * @param source is the source object of the progress
- * @param info is some information from the source object
- * @param percent is the progress of the object (0-100)
- */
- public void progressUpdate(S source, D info, double percent);
+
+ /**
+ * This method is called when the progress is updated
+ *
+ * @param source is the source object of the progress
+ * @param info is some information from the source object
+ * @param percent is the progress of the object (0-100)
+ */
+ public void progressUpdate(S source, D info, double percent);
}
diff --git a/src/zutil/algo/EuclideansAlgo.java b/src/zutil/algo/EuclideansAlgo.java
index fad0554..6f14145 100644
--- a/src/zutil/algo/EuclideansAlgo.java
+++ b/src/zutil/algo/EuclideansAlgo.java
@@ -38,104 +38,104 @@ import java.util.LinkedList;
*/
public class EuclideansAlgo {
- /**
- * Simple Test
- * @param args
- */
- public static void main(String[] args){
- MultiPrintStream.out.println("*** Correct Answer: ");
- MultiPrintStream.out.println("java.util.LinkedList{0, 2, 1, 1, 1, 4, 12, 102, 1, 1, 2, 3, 2, 2, 36}");
- MultiPrintStream.out.println("GCD: 1");
-
- MultiPrintStream.out.println("*** Integer:");
- MultiPrintStream.out.dump(calcGenerators(60728973, 160523347));
- MultiPrintStream.out.println("GCD: "+calc(60728973, 160523347));
-
- MultiPrintStream.out.println("*** BigInteger: ");
- MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347")));
- MultiPrintStream.out.println("GCD: "+calc(new BigInteger("60728973"), new BigInteger("160523347")));
- }
-
- /**
- * Runs the Euclidean algorithm on the two input
- * values.
- *
- * @param a is the first integer
- * @param b is the second integer
- * @return a integer containing the GCD of the integers
- */
- public static int calc(int a, int b){
- int t;
- while( b != 0 ){
- t = b;
- b = a % b;
- a = t;
- }
+ /**
+ * Simple Test
+ * @param args
+ */
+ public static void main(String[] args){
+ MultiPrintStream.out.println("*** Correct Answer: ");
+ MultiPrintStream.out.println("java.util.LinkedList{0, 2, 1, 1, 1, 4, 12, 102, 1, 1, 2, 3, 2, 2, 36}");
+ MultiPrintStream.out.println("GCD: 1");
- return a;
- }
-
- /**
- * Runs the Euclidean algorithm on the two input
- * values.
- *
- * @param a is the first BigInteger
- * @param b is the second BigInteger
- * @return a BigInteger containing the GCD of the BigIntegers
- */
- public static BigInteger calc(BigInteger a, BigInteger b){
- BigInteger t;
-
- while( !b.equals(BigInteger.ZERO) ){
- t = b;
- b = a.mod( b );
- a = t;
- }
+ MultiPrintStream.out.println("*** Integer:");
+ MultiPrintStream.out.dump(calcGenerators(60728973, 160523347));
+ MultiPrintStream.out.println("GCD: "+calc(60728973, 160523347));
- return a;
- }
+ MultiPrintStream.out.println("*** BigInteger: ");
+ MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347")));
+ MultiPrintStream.out.println("GCD: "+calc(new BigInteger("60728973"), new BigInteger("160523347")));
+ }
- /**
- * Runs the Euclidean algorithm on the two input
- * values to find the generators for the values.
- *
- * @param a is the first integer
- * @param b is the second integer
- * @return a list of integers that is generators for a and b
- */
- public static LinkedList calcGenerators(int a, int b){
- LinkedList list = new LinkedList();
- int t;
-
- while( b != 0 ){
- list.add( a/b );
- t = b;
- b = a % b;
- a = t;
- }
-
- return list;
- }
-
- /**
- * Runs the Euclidean algorithm on the two input
- * values to find the generators for the values.
- *
- * @param a is the first BigInteger
- * @param b is the second BigInteger
- * @return a list of BigIntegers that is generators of a and b
- */
- public static LinkedList calcGenerators(BigInteger a, BigInteger b){
- LinkedList list = new LinkedList();
- BigInteger t;
-
- while( !b.equals(BigInteger.ZERO) ){
- list.add( new BigInteger("0").add( a.divide( b ) ) );
- t = b;
- b = a.mod( b );
- a = t;
- }
+ /**
+ * Runs the Euclidean algorithm on the two input
+ * values.
+ *
+ * @param a is the first integer
+ * @param b is the second integer
+ * @return a integer containing the GCD of the integers
+ */
+ public static int calc(int a, int b){
+ int t;
+ while( b != 0 ){
+ t = b;
+ b = a % b;
+ a = t;
+ }
- return list;
- }
+ return a;
+ }
+
+ /**
+ * Runs the Euclidean algorithm on the two input
+ * values.
+ *
+ * @param a is the first BigInteger
+ * @param b is the second BigInteger
+ * @return a BigInteger containing the GCD of the BigIntegers
+ */
+ public static BigInteger calc(BigInteger a, BigInteger b){
+ BigInteger t;
+
+ while( !b.equals(BigInteger.ZERO) ){
+ t = b;
+ b = a.mod( b );
+ a = t;
+ }
+
+ return a;
+ }
+
+ /**
+ * Runs the Euclidean algorithm on the two input
+ * values to find the generators for the values.
+ *
+ * @param a is the first integer
+ * @param b is the second integer
+ * @return a list of integers that is generators for a and b
+ */
+ public static LinkedList calcGenerators(int a, int b){
+ LinkedList list = new LinkedList();
+ int t;
+
+ while( b != 0 ){
+ list.add( a/b );
+ t = b;
+ b = a % b;
+ a = t;
+ }
+
+ return list;
+ }
+
+ /**
+ * Runs the Euclidean algorithm on the two input
+ * values to find the generators for the values.
+ *
+ * @param a is the first BigInteger
+ * @param b is the second BigInteger
+ * @return a list of BigIntegers that is generators of a and b
+ */
+ public static LinkedList calcGenerators(BigInteger a, BigInteger b){
+ LinkedList list = new LinkedList();
+ BigInteger t;
+
+ while( !b.equals(BigInteger.ZERO) ){
+ list.add( new BigInteger("0").add( a.divide( b ) ) );
+ t = b;
+ b = a.mod( b );
+ a = t;
+ }
+
+ return list;
+ }
}
diff --git a/src/zutil/algo/ShanksTonelliAlgo.java b/src/zutil/algo/ShanksTonelliAlgo.java
index dfb100d..e39da39 100644
--- a/src/zutil/algo/ShanksTonelliAlgo.java
+++ b/src/zutil/algo/ShanksTonelliAlgo.java
@@ -36,76 +36,76 @@ import java.math.BigInteger;
* @see Wikipedia
*/
public class ShanksTonelliAlgo {
- public static BigInteger calc(BigInteger n, BigInteger p){
-
- BigInteger nOrg = n;
- BigInteger S = null, V, R, U, X;
- BigInteger ONE = BigInteger.ONE;
- BigInteger TWO = BigInteger.valueOf( 2 );
- BigInteger Q = p.add( ONE ).divide( TWO );
+ public static BigInteger calc(BigInteger n, BigInteger p){
- switch( p.mod( BigInteger.valueOf(4) ).intValue() ){
- case 3:
- S = n.pow( Q.divide( TWO ).intValue() ).mod( p );
- break;
- case 1:
- S = ONE;
- n = n.subtract( ONE );
- while (n.divide( p ).compareTo( ONE ) == 0) {
- S = S.add( ONE );
- //n = (n-2s+1) mod p
- n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p );
- if (n.compareTo( BigInteger.ZERO ) == 0){
- return S;
- }
- }
- Q = Q.divide( TWO );
- V = ONE;
- R = S;
- U = ONE;
- while (Q.compareTo( BigInteger.ZERO ) > 0) {
- X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p );
- U = TWO.multiply( R ).multiply( U ).mod( p );
- R = X;
- if ( Q.testBit(0) ){
- X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p );
- V = V.multiply(R).add( S.multiply(U) ).mod( p );
- S = X;
- }
- Q = Q.divide( TWO );
- }
- }
+ BigInteger nOrg = n;
+ BigInteger S = null, V, R, U, X;
+ BigInteger ONE = BigInteger.ONE;
+ BigInteger TWO = BigInteger.valueOf( 2 );
+ BigInteger Q = p.add( ONE ).divide( TWO );
- if( S != null && S.multiply( S ).mod( p ).compareTo( nOrg ) != 0 ){
- return null;
- }
+ switch( p.mod( BigInteger.valueOf(4) ).intValue() ){
+ case 3:
+ S = n.pow( Q.divide( TWO ).intValue() ).mod( p );
+ break;
+ case 1:
+ S = ONE;
+ n = n.subtract( ONE );
+ while (n.divide( p ).compareTo( ONE ) == 0) {
+ S = S.add( ONE );
+ //n = (n-2s+1) mod p
+ n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p );
+ if (n.compareTo( BigInteger.ZERO ) == 0){
+ return S;
+ }
+ }
+ Q = Q.divide( TWO );
+ V = ONE;
+ R = S;
+ U = ONE;
+ while (Q.compareTo( BigInteger.ZERO ) > 0) {
+ X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p );
+ U = TWO.multiply( R ).multiply( U ).mod( p );
+ R = X;
+ if ( Q.testBit(0) ){
+ X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p );
+ V = V.multiply(R).add( S.multiply(U) ).mod( p );
+ S = X;
+ }
+ Q = Q.divide( TWO );
+ }
+ }
- return S;
- /*
-
- //p-1 = Q*2^S
- BigInteger S = null, Q = null, R = null, V = null, W = null;
+ if( S != null && S.multiply( S ).mod( p ).compareTo( nOrg ) != 0 ){
+ return null;
+ }
- //Q = ( 2^S )/( 1-p );
- p-1 = ( 2^S )/( 1-p ) * 2^S;
+ return S;
+ /*
- // R = n^( (Q+1)/2 ) mod p
- R = n.pow( Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue() ).mod( p );
- // V = W^Q mod p
- V = W.pow( Q.intValue() ).mod( p );
+ //p-1 = Q*2^S
+ BigInteger S = null, Q = null, R = null, V = null, W = null;
- for(int i=S.intValue(); true ;){
- while( true ){
- i--;
- // 1 = ( ( R^2 * n^-1 )^2^i ) mod p
- if( ( R.pow(2).multiply( n.pow(-1) ) ).pow( (int)Math.pow(2, i) ).mod( p ).compareTo( BigInteger.ONE ) == 0 )
- break;
- }
+ //Q = ( 2^S )/( 1-p );
+ p-1 = ( 2^S )/( 1-p ) * 2^S;
- if(i == 0) return R;
- //R = ( RV^(2^(S-i-1)) ) mod p
- else R = ( R.multiply( V.pow( (int)Math.pow( 2, S.intValue()-i-1) ) )).mod( p );
- }
- */
- }
+ // R = n^( (Q+1)/2 ) mod p
+ R = n.pow( Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue() ).mod( p );
+ // V = W^Q mod p
+ V = W.pow( Q.intValue() ).mod( p );
+
+ for(int i=S.intValue(); true ;){
+ while( true ){
+ i--;
+ // 1 = ( ( R^2 * n^-1 )^2^i ) mod p
+ if( ( R.pow(2).multiply( n.pow(-1) ) ).pow( (int)Math.pow(2, i) ).mod( p ).compareTo( BigInteger.ONE ) == 0 )
+ break;
+ }
+
+ if(i == 0) return R;
+ //R = ( RV^(2^(S-i-1)) ) mod p
+ else R = ( R.multiply( V.pow( (int)Math.pow( 2, S.intValue()-i-1) ) )).mod( p );
+ }
+ */
+ }
}
diff --git a/src/zutil/algo/WienersAlgo.java b/src/zutil/algo/WienersAlgo.java
index 165db1c..fc3784d 100644
--- a/src/zutil/algo/WienersAlgo.java
+++ b/src/zutil/algo/WienersAlgo.java
@@ -38,56 +38,56 @@ import java.util.LinkedList;
*
*/
public class WienersAlgo {
-
- /**
- * Runs the Wieners algorithm for the given values.
- *
- * @param n is the first value
- * @param e is the second value
- * @return a BigInteger array of length two.
- * First index is p and second is q.
- * If no value was found then it returns null.
- */
- public static BigInteger[] calc(BigInteger n, BigInteger e){
- BigInteger[] ret = null;
-
- LinkedList gen = EuclideansAlgo.calcGenerators(e, n);
-
- BigInteger c0 = BigInteger.ONE;
- BigInteger c1 = gen.poll();
- BigInteger d0 = BigInteger.ZERO;
- BigInteger d1 = BigInteger.ONE;
-
- BigInteger t, n1, g;
- while(!gen.isEmpty()){
- g = gen.poll();
-
- t = c1;
- c1 = g.multiply( c1 ).add( c0 );
- c0 = t;
-
- t = d1;
- d1 = g.multiply( d1 ).add( d0 );
- d0 = t;
-
- // (d1*e-1) % c1 == 0
- n1 = d1.multiply( e ).subtract( BigInteger.ONE );
- if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){
- n1 = n1.divide( c1 );
-
- // x^2 - ( n - n1 +1 )x + n = 0
- ret = ZMath.pqFormula(
- n.subtract( n1 ).add( BigInteger.ONE ).negate(),
- n);
-
- if(ret[0].compareTo( BigInteger.ZERO ) >= 0 &&
- ret[1].compareTo( BigInteger.ZERO ) >= 0 &&
- ret[0].multiply( ret[1] ).equals( n )){
- return ret;
- }
- }
- }
-
- return null;
- }
+
+ /**
+ * Runs the Wieners algorithm for the given values.
+ *
+ * @param n is the first value
+ * @param e is the second value
+ * @return a BigInteger array of length two.
+ * First index is p and second is q.
+ * If no value was found then it returns null.
+ */
+ public static BigInteger[] calc(BigInteger n, BigInteger e){
+ BigInteger[] ret = null;
+
+ LinkedList gen = EuclideansAlgo.calcGenerators(e, n);
+
+ BigInteger c0 = BigInteger.ONE;
+ BigInteger c1 = gen.poll();
+ BigInteger d0 = BigInteger.ZERO;
+ BigInteger d1 = BigInteger.ONE;
+
+ BigInteger t, n1, g;
+ while(!gen.isEmpty()){
+ g = gen.poll();
+
+ t = c1;
+ c1 = g.multiply( c1 ).add( c0 );
+ c0 = t;
+
+ t = d1;
+ d1 = g.multiply( d1 ).add( d0 );
+ d0 = t;
+
+ // (d1*e-1) % c1 == 0
+ n1 = d1.multiply( e ).subtract( BigInteger.ONE );
+ if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){
+ n1 = n1.divide( c1 );
+
+ // x^2 - ( n - n1 +1 )x + n = 0
+ ret = ZMath.pqFormula(
+ n.subtract( n1 ).add( BigInteger.ONE ).negate(),
+ n);
+
+ if(ret[0].compareTo( BigInteger.ZERO ) >= 0 &&
+ ret[1].compareTo( BigInteger.ZERO ) >= 0 &&
+ ret[0].multiply( ret[1] ).equals( n )){
+ return ret;
+ }
+ }
+ }
+
+ return null;
+ }
}
diff --git a/src/zutil/algo/path/BreadthFirstSearch.java b/src/zutil/algo/path/BreadthFirstSearch.java
index 602543c..90d5f6f 100644
--- a/src/zutil/algo/path/BreadthFirstSearch.java
+++ b/src/zutil/algo/path/BreadthFirstSearch.java
@@ -30,42 +30,42 @@ import java.util.Queue;
/**
* A class that uses BFS to find a path
- *
+ *
* @author Ziver
*/
public class BreadthFirstSearch implements PathFinder{
- /**
- * Returns the first path to the destination
- *
- * @param start is the start Node
- * @param stop is the goal Node
- * @return A list with the path
- */
- public LinkedList find(PathNode start, PathNode stop){
- Queue queue = new LinkedList();
- HashSet visited = new HashSet();
-
- queue.add(start);
- visited.add( start );
-
- PathNode tmp;
- while(!queue.isEmpty()){
- tmp = queue.poll();
-
- for(PathNode next : tmp.getNeighbors()){
- if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){
- queue.add(next);
- visited.add( next );
- next.setParentNeighbor(tmp);
-
- if(next.equals(stop)){
- return stop.traversTo(start);
- }
- }
- }
- }
-
- return new LinkedList();
- }
+ /**
+ * Returns the first path to the destination
+ *
+ * @param start is the start Node
+ * @param stop is the goal Node
+ * @return A list with the path
+ */
+ public LinkedList find(PathNode start, PathNode stop){
+ Queue queue = new LinkedList();
+ HashSet visited = new HashSet();
+
+ queue.add(start);
+ visited.add( start );
+
+ PathNode tmp;
+ while(!queue.isEmpty()){
+ tmp = queue.poll();
+
+ for(PathNode next : tmp.getNeighbors()){
+ if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){
+ queue.add(next);
+ visited.add( next );
+ next.setParentNeighbor(tmp);
+
+ if(next.equals(stop)){
+ return stop.traversTo(start);
+ }
+ }
+ }
+ }
+
+ return new LinkedList<>();
+ }
}
diff --git a/src/zutil/algo/path/DepthFirstSearch.java b/src/zutil/algo/path/DepthFirstSearch.java
index 385d14a..197323d 100644
--- a/src/zutil/algo/path/DepthFirstSearch.java
+++ b/src/zutil/algo/path/DepthFirstSearch.java
@@ -33,42 +33,42 @@ import java.util.LinkedList;
* @author Ziver
*/
public class DepthFirstSearch {
- private HashSet visited = new HashSet();
+ private HashSet visited = new HashSet();
- /**
- * Returns the first path to the destination
- *
- * @param start Start Node
- * @param stop Stop Node
- * @return A list with the path
- */
- public LinkedList find(PathNode start, PathNode stop){
- visited.clear();
- PathNode node = dfs(start, stop);
- return node.traversTo( start );
- }
+ /**
+ * Returns the first path to the destination
+ *
+ * @param start Start Node
+ * @param stop Stop Node
+ * @return A list with the path
+ */
+ public LinkedList find(PathNode start, PathNode stop){
+ visited.clear();
+ PathNode node = dfs(start, stop);
+ return node.traversTo( start );
+ }
- /**
- * The DepthFirstSearch algorithm
- * @param node The node to search from
- * @return The stop PathNode if a path was found else null
- */
- private PathNode dfs(PathNode node, PathNode stop){
- visited.add( node );
- if(node.equals(stop)){
- return node;
- }
+ /**
+ * The DepthFirstSearch algorithm
+ * @param node The node to search from
+ * @return The stop PathNode if a path was found else null
+ */
+ private PathNode dfs(PathNode node, PathNode stop){
+ visited.add( node );
+ if(node.equals(stop)){
+ return node;
+ }
- for(PathNode next : node.getNeighbors()){
- if(!visited.contains( next ) && node.getNeighborCost(next) > 0){
- next.setParentNeighbor(node);
- PathNode tmp = dfs(next, stop);
- if(tmp != null){
- return tmp;
- }
- }
- }
- return null;
- }
+ for(PathNode next : node.getNeighbors()){
+ if(!visited.contains( next ) && node.getNeighborCost(next) > 0){
+ next.setParentNeighbor(node);
+ PathNode tmp = dfs(next, stop);
+ if(tmp != null){
+ return tmp;
+ }
+ }
+ }
+ return null;
+ }
}
diff --git a/src/zutil/algo/path/DynamicProgramming.java b/src/zutil/algo/path/DynamicProgramming.java
index 9652f5a..aa550a9 100644
--- a/src/zutil/algo/path/DynamicProgramming.java
+++ b/src/zutil/algo/path/DynamicProgramming.java
@@ -25,117 +25,117 @@
package zutil.algo.path;
public class DynamicProgramming {
- public static char[][] words = new char[][]{
- "bibba".toCharArray(),
- "bitas".toCharArray(),
- "brott".toCharArray(),
- "bl�ja".toCharArray(),
- "boson".toCharArray()
- };
+ public static char[][] words = new char[][]{
+ "bibba".toCharArray(),
+ "bitas".toCharArray(),
+ "brott".toCharArray(),
+ "bl�ja".toCharArray(),
+ "boson".toCharArray()
+ };
- public static void main(String[] args){
- new DynamicProgramming().search();
- }
- /*
+ public static void main(String[] args){
+ new DynamicProgramming().search();
+ }
+ /*
int search(words[][][])
- matrix[][][] = 0
- shortest = -1
-
- for w=0->length(words)
- for y=0->length(words)
- for x=0->length(words)
- // f�rsta raden i matrisen
- if y == 0
- // finns f�rsta bokstaven i r�tt position i f�rsta ordet?
- if words[0][x] != words[w][0]
- matrix[w][y][x] = -1
- else
- matrix[w][y][x] = 0
- else
- // om f�reg�ende �r negativ s�tt nuvarande till negativ
- if matrix[w][y-1][x] < 0
- matrix[w][y-1][x] = -1
- // h�r s� h�nder det riktiga i algoritmen
- else
- tmp = minstaForskjutning(words[y], words[w][y], x)
- if tmp >= 0
- matrix[w][y][x] = matrix[w][y-1][x] + tmp
- else
- matrix[w][y][x] = -1
- // kolla om det �r sista raden i matrisen
- if y == length(matrix)
- if (tmp < shortest || shortest < 0) && tmp >= 0
- shortest = tmp;
-
- return shortest
-
+ matrix[][][] = 0
+ shortest = -1
+
+ for w=0->length(words)
+ for y=0->length(words)
+ for x=0->length(words)
+ // f�rsta raden i matrisen
+ if y == 0
+ // finns f�rsta bokstaven i r�tt position i f�rsta ordet?
+ if words[0][x] != words[w][0]
+ matrix[w][y][x] = -1
+ else
+ matrix[w][y][x] = 0
+ else
+ // om f�reg�ende �r negativ s�tt nuvarande till negativ
+ if matrix[w][y-1][x] < 0
+ matrix[w][y-1][x] = -1
+ // h�r s� h�nder det riktiga i algoritmen
+ else
+ tmp = minstaForskjutning(words[y], words[w][y], x)
+ if tmp >= 0
+ matrix[w][y][x] = matrix[w][y-1][x] + tmp
+ else
+ matrix[w][y][x] = -1
+ // kolla om det �r sista raden i matrisen
+ if y == length(matrix)
+ if (tmp < shortest || shortest < 0) && tmp >= 0
+ shortest = tmp;
+
+ return shortest
+
int minstaForskjutning(word[], find, index){
- minsta = -1
- for i=0->length(word)
- if word[i] == cfind && (abs(index-i) < minsta || minsta < 0)
- minsta = abs(index-i)
-
- return minsta
-
- */
+ minsta = -1
+ for i=0->length(word)
+ if word[i] == cfind && (abs(index-i) < minsta || minsta < 0)
+ minsta = abs(index-i)
- public int search(){
- int[][][] matrix = new int[words.length][words.length][words.length];
- int shortest = -1;
+ return minsta
- for(int w=0; w= 0){
- matrix[w][y][x] = matrix[w][y-1][x] + tmp;
- }
- else{
- matrix[w][y][x] = -1;
- }
- }
- }
- if(y == words.length-1){
- int tmp = matrix[w][y][x];
- if((tmp= 0){
- shortest = tmp;
- }
- }
- System.out.print(" "+matrix[w][y][x]);
- }
- }
- }
+ */
- System.out.println("\n\nKortaste f�rflyttningen: "+shortest);
- return shortest;
- }
+ public int search(){
+ int[][][] matrix = new int[words.length][words.length][words.length];
+ int shortest = -1;
- private int minstaForskjutning(char[] word, char cfind, int index){
- int minsta = -1;
- for(int i=0; i= 0){
+ matrix[w][y][x] = matrix[w][y-1][x] + tmp;
+ }
+ else{
+ matrix[w][y][x] = -1;
+ }
+ }
+ }
+ if(y == words.length-1){
+ int tmp = matrix[w][y][x];
+ if((tmp= 0){
+ shortest = tmp;
+ }
+ }
+ System.out.print(" "+matrix[w][y][x]);
+ }
+ }
+ }
+
+ System.out.println("\n\nKortaste f�rflyttningen: "+shortest);
+ return shortest;
+ }
+
+ private int minstaForskjutning(char[] word, char cfind, int index){
+ int minsta = -1;
+ for(int i=0; i find(PathNode start, PathNode goal);
+ /**
+ * Starts the search for the path from the start
+ * node to the goal.
+ *
+ * @param start is the starting point of the search
+ * @param goal is the search goal
+ * @return a LinkedList of the path, empty list if no path was found
+ */
+ public LinkedList find(PathNode start, PathNode goal);
}
diff --git a/src/zutil/algo/path/PathNode.java b/src/zutil/algo/path/PathNode.java
index 4cce8ac..13e94e1 100644
--- a/src/zutil/algo/path/PathNode.java
+++ b/src/zutil/algo/path/PathNode.java
@@ -29,32 +29,32 @@ import java.util.LinkedList;
public interface PathNode {
- /**
- * @return an Iterator with all its neighbors
- */
- public Iterable getNeighbors();
-
- /**
- * @param neighbor is the neighbor
- * @return the cost to the neighbor
- */
- public int getNeighborCost(PathNode neighbor);
-
- /**
- * Sets the parent node to this one
- */
- public void setParentNeighbor(PathNode parent);
-
- /**
- * @return the parent node
- */
- public PathNode getParentNeighbor();
-
- /**
- * Traverses the parent tree and returns the path.
- *
- * @param goal is the node to reach
- * @return the path to the goal, empty list if there is no goal
- */
- public LinkedList traversTo(PathNode goal);
+ /**
+ * @return an Iterator with all its neighbors
+ */
+ public Iterable getNeighbors();
+
+ /**
+ * @param neighbor is the neighbor
+ * @return the cost to the neighbor
+ */
+ public int getNeighborCost(PathNode neighbor);
+
+ /**
+ * Sets the parent node to this one
+ */
+ public void setParentNeighbor(PathNode parent);
+
+ /**
+ * @return the parent node
+ */
+ public PathNode getParentNeighbor();
+
+ /**
+ * Traverses the parent tree and returns the path.
+ *
+ * @param goal is the node to reach
+ * @return the path to the goal, empty list if there is no goal
+ */
+ public LinkedList traversTo(PathNode goal);
}
diff --git a/src/zutil/algo/path/StandardPathNode.java b/src/zutil/algo/path/StandardPathNode.java
index 87c7409..e828e6c 100644
--- a/src/zutil/algo/path/StandardPathNode.java
+++ b/src/zutil/algo/path/StandardPathNode.java
@@ -33,32 +33,32 @@ import java.util.LinkedList;
*
*/
public class StandardPathNode implements PathNode{
- private HashMap neighbors;
- private PathNode parent;
-
- public StandardPathNode(){
- neighbors = new HashMap();
- }
+ private HashMap neighbors;
+ private PathNode parent;
- public int getNeighborCost(PathNode neighbor) {
- return neighbors.get(neighbor);
- }
+ public StandardPathNode(){
+ neighbors = new HashMap();
+ }
- public Iterable getNeighbors() {
- return neighbors.keySet();
- }
+ public int getNeighborCost(PathNode neighbor) {
+ return neighbors.get(neighbor);
+ }
- public PathNode getParentNeighbor() {
- return parent;
- }
+ public Iterable getNeighbors() {
+ return neighbors.keySet();
+ }
- public void setParentNeighbor(PathNode parent) {
- this.parent = parent;
- }
+ public PathNode getParentNeighbor() {
+ return parent;
+ }
- public LinkedList traversTo(PathNode goal) {
- LinkedList path = new LinkedList();
- PathNode current = this;
+ public void setParentNeighbor(PathNode parent) {
+ this.parent = parent;
+ }
+
+ public LinkedList traversTo(PathNode goal) {
+ LinkedList path = new LinkedList();
+ PathNode current = this;
while(current != null){
path.addFirst(current);
current = current.getParentNeighbor();
@@ -68,6 +68,6 @@ public class StandardPathNode implements PathNode{
}
}
return new LinkedList();
- }
+ }
}
diff --git a/src/zutil/algo/search/QuickSelect.java b/src/zutil/algo/search/QuickSelect.java
index 7d70fc7..f966b0d 100644
--- a/src/zutil/algo/search/QuickSelect.java
+++ b/src/zutil/algo/search/QuickSelect.java
@@ -36,57 +36,57 @@ import zutil.algo.sort.sortable.SortableDataList;
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class QuickSelect {
-
- public static Object find(SortableDataList list, int k){
- return find(list, k, 0, list.size()-1);
- }
-
- /*
- function select(list, k, left, right)
- select a pivot value list[pivotIndex]
- pivotNewIndex := partition(list, left, right, pivotIndex)
- if k = pivotNewIndex
- return list[k]
- else if k < pivotNewIndex
- return select(list, k, left, pivotNewIndex-1)
- else
- return select(list, k, pivotNewIndex+1, right)
- */
- public static Object find(SortableDataList list, int k, int left, int right){
- // select a pivot
- int pivot = right/2;
- int newPivot = partition(list, left, right, pivot);
- if(k == newPivot)
- return list.get(k);
- else if(k < newPivot)
- return find(list, k, left, newPivot-1);
- else
- return find(list, k, newPivot+1, right);
- }
-
- /*
- function partition(list, left, right, pivotIndex)
- pivotValue := list[pivotIndex]
- swap list[pivotIndex] and list[right] // Move pivot to end
- storeIndex := left
- for i from left to right-1
- if list[i] < pivotValue
- swap list[storeIndex] and list[i]
- storeIndex := storeIndex + 1
- swap list[right] and list[storeIndex] // Move pivot to its final place
- return storeIndex
- */
- private static int partition(SortableDataList list, int left, int right, int pivot){
- Object pivotValue = list.get(pivot);
- list.swap(pivot, right);
- int storeIndex = left;
- for(int i=left; i chunkFiles = sortChunks();
+ /**
+ * Creates a ExternalSort object that sort a big file
+ * with minimal use of ram
+ *
+ * @param orgFile File to sort
+ * @param sortedFile The sorted file
+ * @param chunk The chunk size
+ * @throws FileNotFoundException
+ */
+ public ExternalSort(File orgFile, File sortedFile, int chunk) throws FileNotFoundException{
+ in = new BufferedReader(new FileReader(orgFile));
+ this.sortedFile = sortedFile;
+ CHUNK_SIZE = chunk;
+ }
- //merging the chunks
- mergeFiles(chunkFiles);
+ /**
+ * Sorts the given file
+ *
+ * @throws IOException Some kind of error
+ */
+ public void sort() throws IOException{
+ // sorting the chunks
+ LinkedList chunkFiles = sortChunks();
- //removing the chunks
- removeFiles(chunkFiles);
- }
+ //merging the chunks
+ mergeFiles(chunkFiles);
- /**
- * Merges all the files to one
- * @param files
- */
- private void mergeFiles(LinkedList files){
- try {
- BufferedReader[] chunkReader = new BufferedReader[files.size()];
- String[] rows = new String[files.size()];
- BufferedWriter out = new BufferedWriter(new FileWriter(sortedFile));
+ //removing the chunks
+ removeFiles(chunkFiles);
+ }
- boolean someFileStillHasRows = false;
+ /**
+ * Merges all the files to one
+ * @param files
+ */
+ private void mergeFiles(LinkedList files){
+ try {
+ BufferedReader[] chunkReader = new BufferedReader[files.size()];
+ String[] rows = new String[files.size()];
+ BufferedWriter out = new BufferedWriter(new FileWriter(sortedFile));
- for (int i=0; i sortChunks() throws IOException{
- LinkedList chunkFiles = new LinkedList();
- LinkedList chunk = new LinkedList();
- do{
- chunk = readChunk(in);
+ // check if one still has rows
+ someFileStillHasRows = false;
+ for(int i=0; i sortChunks() throws IOException{
+ LinkedList chunkFiles = new LinkedList();
+ LinkedList chunk = new LinkedList();
+ do{
+ chunk = readChunk(in);
- return chunkFiles;
- }
+ //QuickSort.sort(new SortableLinkedList(chunk));
+ Collections.sort(chunk);
- /**
- * Reads in a chunk of rows into a LinkedList
- *
- * @param list The list to populate
- * @param in The BufferedReader to read from
- * @return The LinkeList with the chunk
- * @throws IOException Some kind of error
- */
- private LinkedList readChunk(BufferedReader in) throws IOException{
- LinkedList list = new LinkedList();
- String tmp;
- for(int i=0; i list, File file) throws IOException{
- BufferedWriter out = new BufferedWriter(new FileWriter(file));
- Iterator it = list.iterator();
- while(it.hasNext()){
- out.write(it.next());
- out.newLine();
- }
- out.close();
- }
+ return chunkFiles;
+ }
- private void removeFiles(LinkedList list){
- Iterator it = list.iterator();
- while(it.hasNext()){
- it.next().delete();
- }
- }
+ /**
+ * Reads in a chunk of rows into a LinkedList
+ *
+ * @param list The list to populate
+ * @param in The BufferedReader to read from
+ * @return The LinkeList with the chunk
+ * @throws IOException Some kind of error
+ */
+ private LinkedList readChunk(BufferedReader in) throws IOException{
+ LinkedList list = new LinkedList();
+ String tmp;
+ for(int i=0; i list, File file) throws IOException{
+ BufferedWriter out = new BufferedWriter(new FileWriter(file));
+ Iterator it = list.iterator();
+ while(it.hasNext()){
+ out.write(it.next());
+ out.newLine();
+ }
+ out.close();
+ }
+
+ private void removeFiles(LinkedList list){
+ Iterator it = list.iterator();
+ while(it.hasNext()){
+ it.next().delete();
+ }
+ }
}
diff --git a/src/zutil/algo/sort/MergeSort.java b/src/zutil/algo/sort/MergeSort.java
index e151e0e..55195f8 100644
--- a/src/zutil/algo/sort/MergeSort.java
+++ b/src/zutil/algo/sort/MergeSort.java
@@ -29,131 +29,131 @@ import zutil.algo.sort.sortable.SortableDataList;
public class MergeSort{
- /**
- * Sorts the given list with Merge sort
- *
- * @param list is the list to sort
- */
- public static void sort(int[] list){
- if(list == null)
- return;
-
- sort(list, 0, list.length);
- }
+ /**
+ * Sorts the given list with Merge sort
+ *
+ * @param list is the list to sort
+ */
+ public static void sort(int[] list){
+ if(list == null)
+ return;
- /**
- * This method is the array splitting method
- * that recursively splits the array in two.
- *
- * @param list is the list to sort
- * @param start is the starting index of the sub list
- * @param stop is the end index of the sub list
- */
- protected static void sort(int[] list, int start, int stop){
- if(stop-start <= 1) return;
+ sort(list, 0, list.length);
+ }
- int pivot = start+(stop-start)/2;
- sort(list, start, pivot);
- sort(list, pivot, stop);
+ /**
+ * This method is the array splitting method
+ * that recursively splits the array in two.
+ *
+ * @param list is the list to sort
+ * @param start is the starting index of the sub list
+ * @param stop is the end index of the sub list
+ */
+ protected static void sort(int[] list, int start, int stop){
+ if(stop-start <= 1) return;
- merge(list, start, stop, pivot);
- }
+ int pivot = start+(stop-start)/2;
+ sort(list, start, pivot);
+ sort(list, pivot, stop);
- /**
- * This method is the merger, after the array
- * has been split this method will merge the
- * two parts of the array and sort it.
- *
- * @param list is the list to merge
- * @param start is the start of the first sublist
- * @param stop is the end of the second sublist
- * @param pivot is the end index for the first list and the beginning of the second.
- */
- protected static void merge(int[] list, int start, int stop, int pivot){
- int length = pivot-start;
- int[] tmp = new int[stop-start];
+ merge(list, start, stop, pivot);
+ }
- for(int i=0; i= length || tmp[index1] > tmp[index2]) ){
- list[i] = tmp[index2];
- ++index2;
- }
- else {
- list[i] = tmp[index1];
- ++index1;
- }
- }
- }
-
-
- /**
- * Sorts the given list with Merge sort,
- * this is slower than the one with int[] array
- *
- * @param list is the list to sort
- */
- public static void sort(SortableDataList> list){
- if(list == null)
- return;
-
- sort(list, 0, list.size());
- }
+ for(int i=0; i list, int start, int stop){
- if(stop-start <= 1) return;
+ int index1 = 0;
+ int index2 = length;
+ for(int i=start; i= length || tmp[index1] > tmp[index2]) ){
+ list[i] = tmp[index2];
+ ++index2;
+ }
+ else {
+ list[i] = tmp[index1];
+ ++index1;
+ }
+ }
+ }
- int pivot = start+(stop-start)/2;
- sort(list, start, pivot);
- sort(list, pivot, stop);
- merge(list, start, stop, pivot);
- }
+ /**
+ * Sorts the given list with Merge sort,
+ * this is slower than the one with int[] array
+ *
+ * @param list is the list to sort
+ */
+ public static void sort(SortableDataList> list){
+ if(list == null)
+ return;
- /**
- * This method is the merger, after the array
- * has been split this method will merge the
- * two parts of the array and sort it.
- * @param
- *
- * @param list is the list to merge
- * @param start is the start of the first sublist
- * @param stop is the end of the second sublist
- * @param pivot is the end index for the first list and the beginning of the second.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- protected static void merge(SortableDataList list, int start, int stop, int pivot){
- int length = pivot-start;
- Object[] tmp = new Object[stop-start];
+ sort(list, 0, list.size());
+ }
- for(int i=0; i list, int start, int stop){
+ if(stop-start <= 1) return;
- int index1 = 0;
- int index2 = length;
- for(int i=start; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){
- list.set(i, (T)tmp[index2]);
- ++index2;
- }
- else {
- list.set(i, (T)tmp[index1]);
- ++index1;
- }
- }
- }
+ int pivot = start+(stop-start)/2;
+ sort(list, start, pivot);
+ sort(list, pivot, stop);
+
+ merge(list, start, stop, pivot);
+ }
+
+ /**
+ * This method is the merger, after the array
+ * has been split this method will merge the
+ * two parts of the array and sort it.
+ * @param
+ *
+ * @param list is the list to merge
+ * @param start is the start of the first sublist
+ * @param stop is the end of the second sublist
+ * @param pivot is the end index for the first list and the beginning of the second.
+ */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ protected static void merge(SortableDataList list, int start, int stop, int pivot){
+ int length = pivot-start;
+ Object[] tmp = new Object[stop-start];
+
+ for(int i=0; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){
+ list.set(i, (T)tmp[index2]);
+ ++index2;
+ }
+ else {
+ list.set(i, (T)tmp[index1]);
+ ++index1;
+ }
+ }
+ }
}
diff --git a/src/zutil/algo/sort/QuickSort.java b/src/zutil/algo/sort/QuickSort.java
index 59184e7..dd1ebef 100644
--- a/src/zutil/algo/sort/QuickSort.java
+++ b/src/zutil/algo/sort/QuickSort.java
@@ -33,17 +33,17 @@ import zutil.algo.sort.sortable.SortableDataList;
* @author Ziver
*/
public class QuickSort{
- public static final int RANDOM_PIVOT = 0;
- public static final int MEDIAN_PIVOT = 1;
- public static final int MIDDLE_PIVOT = 2;
-
+ public static final int RANDOM_PIVOT = 0;
+ public static final int MEDIAN_PIVOT = 1;
+ public static final int MIDDLE_PIVOT = 2;
+
/**
* Sort the elements in ascending order using Quicksort.
*
* @param list is the list to sort.
*/
- public static void sort(SortableDataList> list){
- sort(list, 0, list.size()-1, MIDDLE_PIVOT, true);
+ public static void sort(SortableDataList> list){
+ sort(list, 0, list.size()-1, MIDDLE_PIVOT, true);
}
/**
@@ -53,10 +53,10 @@ public class QuickSort{
* @param type is the type of pivot
* @param insert is if insertion sort will be used
*/
- public static void sort(SortableDataList> list, int type, boolean insert){
- sort(list, 0, list.size()-1, type, insert);
+ public static void sort(SortableDataList> list, int type, boolean insert){
+ sort(list, 0, list.size()-1, type, insert);
}
-
+
/**
* Sort the elements in ascending order using Quicksort.
* Reference: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm
@@ -67,59 +67,59 @@ public class QuickSort{
* @param stop is the index to stop
* @param type is the type of pivot to use
*/
- @SuppressWarnings({ "unchecked", "rawtypes" })
- public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){
- if(stop-start <= 15 && insertionSort){
- SimpleSort.insertionSort( list, start, stop);
- }
- int pivotIndex = pivot(list,start,stop,type);
- Object pivot = list.get(pivotIndex);
- int left=start, right=stop;
-
- do{
- while(list.compare(left, pivot) < 0){
- left++;
- }
- while(list.compare(right, pivot) > 0){
- right--;
- }
-
- if(left <= right){
- list.swap(left, right);
- left++;
- right--;
- }
- }while(left <= right);
-
- if(start < right){
- sort(list, start, right, type, insertionSort);
- }
- if(left < stop){
- sort(list, left, stop, type, insertionSort);
- }
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){
+ if(stop-start <= 15 && insertionSort){
+ SimpleSort.insertionSort( list, start, stop);
+ }
+ int pivotIndex = pivot(list,start,stop,type);
+ Object pivot = list.get(pivotIndex);
+ int left=start, right=stop;
- }
+ do{
+ while(list.compare(left, pivot) < 0){
+ left++;
+ }
+ while(list.compare(right, pivot) > 0){
+ right--;
+ }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private static int pivot(SortableDataList> list, int start, int stop,int type){
- switch(type){
- case RANDOM_PIVOT:
- return start+(int)(Math.random()*(stop-start));
- case MEDIAN_PIVOT:
- Comparable[] i = new Comparable[]{
- (Comparable)list.get(0),
- (Comparable)list.get(list.size()/2),
- (Comparable)list.get(list.size()-1)};
- SimpleSort.insertionSort(new SortableComparableArray(i));
- if(i[i.length/2].compareTo(list.get(start)) == 0)
- return start;
- else if(i[i.length/2].compareTo(list.get(stop)) == 0)
- return stop;
- else
- return start+(stop-start)/2;
- case MIDDLE_PIVOT:
- return (start+stop)/2;
- }
- return 0;
+ if(left <= right){
+ list.swap(left, right);
+ left++;
+ right--;
+ }
+ }while(left <= right);
+
+ if(start < right){
+ sort(list, start, right, type, insertionSort);
+ }
+ if(left < stop){
+ sort(list, left, stop, type, insertionSort);
+ }
+
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ private static int pivot(SortableDataList> list, int start, int stop,int type){
+ switch(type){
+ case RANDOM_PIVOT:
+ return start+(int)(Math.random()*(stop-start));
+ case MEDIAN_PIVOT:
+ Comparable[] i = new Comparable[]{
+ (Comparable)list.get(0),
+ (Comparable)list.get(list.size()/2),
+ (Comparable)list.get(list.size()-1)};
+ SimpleSort.insertionSort(new SortableComparableArray(i));
+ if(i[i.length/2].compareTo(list.get(start)) == 0)
+ return start;
+ else if(i[i.length/2].compareTo(list.get(stop)) == 0)
+ return stop;
+ else
+ return start+(stop-start)/2;
+ case MIDDLE_PIVOT:
+ return (start+stop)/2;
+ }
+ return 0;
}
}
diff --git a/src/zutil/algo/sort/Randomizer.java b/src/zutil/algo/sort/Randomizer.java
index 77721a7..6887587 100644
--- a/src/zutil/algo/sort/Randomizer.java
+++ b/src/zutil/algo/sort/Randomizer.java
@@ -33,16 +33,16 @@ import zutil.algo.sort.sortable.SortableDataList;
* @author Ziver
*/
public class Randomizer {
-
- /**
- * Randomizes the index of all the elements
- * @param list The list
- */
- @SuppressWarnings({ "rawtypes" })
- public static void sort(SortableDataList list){
- int size = list.size();
- for(int i=0; i implements SortableDataList{
- private ArrayList list;
-
- public SortableArrayList(ArrayList list){
- this.list = list;
- }
+ private ArrayList list;
- public T get(int i) {
- return list.get(i);
- }
-
- public void set(int i, T o){
- list.set(i, o);
- }
+ public SortableArrayList(ArrayList list){
+ this.list = list;
+ }
- public int size() {
- return list.size();
- }
+ public T get(int i) {
+ return list.get(i);
+ }
- public void swap(int a, int b) {
- T temp = list.get(a);
- list.set(a, list.get(b));
- list.set(b, temp);
- }
-
- public int compare(int a, int b) {
- Comparable aa = (Comparable)list.get(a);
- Comparable bb = (Comparable)list.get(b);
- return aa.compareTo(bb);
- }
+ public void set(int i, T o){
+ list.set(i, o);
+ }
- public int compare(int a, T b) {
- Comparable aa = (Comparable)list.get(a);
- Comparable bb = (Comparable)b;
- return aa.compareTo(bb);
- }
-
-
+ public int size() {
+ return list.size();
+ }
+ public void swap(int a, int b) {
+ T temp = list.get(a);
+ list.set(a, list.get(b));
+ list.set(b, temp);
+ }
+
+ public int compare(int a, int b) {
+ Comparable aa = (Comparable)list.get(a);
+ Comparable bb = (Comparable)list.get(b);
+ return aa.compareTo(bb);
+ }
+
+ public int compare(int a, T b) {
+ Comparable aa = (Comparable)list.get(a);
+ Comparable bb = (Comparable)b;
+ return aa.compareTo(bb);
+ }
}
diff --git a/src/zutil/algo/sort/sortable/SortableComparableArray.java b/src/zutil/algo/sort/sortable/SortableComparableArray.java
index 98899ae..7f1112a 100644
--- a/src/zutil/algo/sort/sortable/SortableComparableArray.java
+++ b/src/zutil/algo/sort/sortable/SortableComparableArray.java
@@ -26,50 +26,47 @@ package zutil.algo.sort.sortable;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class SortableComparableArray implements SortableDataList{
- private Comparable[] list;
-
- public SortableComparableArray(Comparable[] list){
- this.list = list;
- }
-
- public Comparable get(int i) {
- return list[i];
- }
-
- public void set(int i, Comparable o){
- list[i] = o;
- }
+ private Comparable[] list;
- public int size() {
- return list.length;
- }
+ public SortableComparableArray(Comparable[] list){
+ this.list = list;
+ }
- public void swap(int a, int b) {
- Comparable temp = list[a];
- list[a] = list[b];
- list[b] = temp;
- }
+ public Comparable get(int i) {
+ return list[i];
+ }
- public int compare(int a, int b) {
- if(list[a].compareTo(list[b]) < 0){
- return -1;
- }
- else if(list[a].compareTo(list[b]) > 0){
- return 1;
- }
- return 0;
- }
+ public void set(int i, Comparable o){
+ list[i] = o;
+ }
- public int compare(int a, Comparable b) {
- if(list[a].compareTo(b) < 0){
- return -1;
- }
- else if(list[a].compareTo(b) > 0){
- return 1;
- }
- return 0;
- }
+ public int size() {
+ return list.length;
+ }
+ public void swap(int a, int b) {
+ Comparable temp = list[a];
+ list[a] = list[b];
+ list[b] = temp;
+ }
+ public int compare(int a, int b) {
+ if(list[a].compareTo(list[b]) < 0){
+ return -1;
+ }
+ else if(list[a].compareTo(list[b]) > 0){
+ return 1;
+ }
+ return 0;
+ }
+ public int compare(int a, Comparable b) {
+ if(list[a].compareTo(b) < 0){
+ return -1;
+ }
+ else if(list[a].compareTo(b) > 0){
+ return 1;
+ }
+ return 0;
+ }
}
diff --git a/src/zutil/algo/sort/sortable/SortableIntArray.java b/src/zutil/algo/sort/sortable/SortableIntArray.java
index 56a4f6d..2701850 100644
--- a/src/zutil/algo/sort/sortable/SortableIntArray.java
+++ b/src/zutil/algo/sort/sortable/SortableIntArray.java
@@ -25,49 +25,49 @@
package zutil.algo.sort.sortable;
public class SortableIntArray implements SortableDataList{
- private int[] list;
-
- public SortableIntArray(int[] list){
- this.list = list;
- }
-
- public Integer get(int i) {
- return list[i];
- }
+ private int[] list;
- public void set(int i, Integer o){
- list[i] = o;
- }
-
- public int size() {
- return list.length;
- }
+ public SortableIntArray(int[] list){
+ this.list = list;
+ }
- public void swap(int a, int b) {
- int temp = list[a];
- list[a] = list[b];
- list[b] = temp;
- }
+ public Integer get(int i) {
+ return list[i];
+ }
- public int compare(int a, int b) {
- if(list[a] < list[b]){
- return -1;
- }
- else if(list[a] > list[b]){
- return 1;
- }
- return 0;
- }
+ public void set(int i, Integer o){
+ list[i] = o;
+ }
- public int compare(int a, Integer b) {
- if(list[a] < b){
- return -1;
- }
- else if(list[a] > b){
- return 1;
- }
- return 0;
- }
+ public int size() {
+ return list.length;
+ }
+
+ public void swap(int a, int b) {
+ int temp = list[a];
+ list[a] = list[b];
+ list[b] = temp;
+ }
+
+ public int compare(int a, int b) {
+ if(list[a] < list[b]){
+ return -1;
+ }
+ else if(list[a] > list[b]){
+ return 1;
+ }
+ return 0;
+ }
+
+ public int compare(int a, Integer b) {
+ if(list[a] < b){
+ return -1;
+ }
+ else if(list[a] > b){
+ return 1;
+ }
+ return 0;
+ }
diff --git a/src/zutil/algo/sort/sortable/SortableLinkedList.java b/src/zutil/algo/sort/sortable/SortableLinkedList.java
index caee2e4..b4c83fd 100644
--- a/src/zutil/algo/sort/sortable/SortableLinkedList.java
+++ b/src/zutil/algo/sort/sortable/SortableLinkedList.java
@@ -28,42 +28,42 @@ import java.util.LinkedList;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class SortableLinkedList implements SortableDataList{
- private LinkedList list;
-
- public SortableLinkedList(LinkedList list){
- this.list = list;
- }
+ private LinkedList list;
- public T get(int i) {
- return list.get(i);
- }
-
- public void set(int i, T o){
- list.set(i, o);
- }
+ public SortableLinkedList(LinkedList list){
+ this.list = list;
+ }
- public int size() {
- return list.size();
- }
+ public T get(int i) {
+ return list.get(i);
+ }
+
+ public void set(int i, T o){
+ list.set(i, o);
+ }
+
+ public int size() {
+ return list.size();
+ }
+
+ public void swap(int a, int b) {
+ T temp = list.get(a);
+ list.set(a, list.get(b));
+ list.set(b, temp);
+ }
+
+ public int compare(int a, int b) {
+ Comparable aa = (Comparable)list.get(a);
+ Comparable bb = (Comparable)list.get(b);
+ return aa.compareTo(bb);
+ }
+
+ public int compare(int a, T b) {
+ Comparable aa = (Comparable)list.get(a);
+ Comparable bb = (Comparable)b;
+ return aa.compareTo(bb);
+ }
- public void swap(int a, int b) {
- T temp = list.get(a);
- list.set(a, list.get(b));
- list.set(b, temp);
- }
-
- public int compare(int a, int b) {
- Comparable aa = (Comparable)list.get(a);
- Comparable bb = (Comparable)list.get(b);
- return aa.compareTo(bb);
- }
- public int compare(int a, T b) {
- Comparable aa = (Comparable)list.get(a);
- Comparable bb = (Comparable)b;
- return aa.compareTo(bb);
- }
-
-
}
diff --git a/src/zutil/converter/Converter.java b/src/zutil/converter/Converter.java
index 0515760..96b5b3a 100755
--- a/src/zutil/converter/Converter.java
+++ b/src/zutil/converter/Converter.java
@@ -33,61 +33,61 @@ import java.util.Iterator;
import java.util.Map;
public class Converter {
- private Converter(){}
+ private Converter(){}
- /**
- * Converts an object to an array of bytes.
- *
- * @param object the object to convert.
- * @return the associated byte array.
- */
- public static byte[] toBytes(Object object) throws IOException{
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ /**
+ * Converts an object to an array of bytes.
+ *
+ * @param object the object to convert.
+ * @return the associated byte array.
+ */
+ public static byte[] toBytes(Object object) throws IOException{
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(object);
- oos.flush();
- oos.close();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(object);
+ oos.flush();
+ oos.close();
- return baos.toByteArray();
- }
-
- /**
- * Converts a Integer to an byte array
- *
- * @param num is the number to convert
- * @return a byte array of four bytes
- */
- public static byte[] toBytes(int num){
- return new byte[]{
- (byte)(num & 0xff),
- (byte)((num >> 8)& 0xff),
- (byte)((num >> 16)& 0xff),
- (byte)((num >> 24)& 0xff)};
- }
+ return baos.toByteArray();
+ }
+
+ /**
+ * Converts a Integer to an byte array
+ *
+ * @param num is the number to convert
+ * @return a byte array of four bytes
+ */
+ public static byte[] toBytes(int num){
+ return new byte[]{
+ (byte)(num & 0xff),
+ (byte)((num >> 8)& 0xff),
+ (byte)((num >> 16)& 0xff),
+ (byte)((num >> 24)& 0xff)};
+ }
/**
* Converts a char array to a byte array.
*
* @return a byte array with the same binary value as the char.
*/
- public static byte[] toBytes(char[] arr){
+ public static byte[] toBytes(char[] arr){
byte[] ret = new byte[arr.length];
- for (int i=0; i>>= 1;
- }
- return str.reverse().toString();
- }
+ public static String toBitString(byte raw){
+ StringBuilder str = new StringBuilder(8);
+ for (int i=0; i<8; ++i) {
+ str.append(raw & 0x01);
+ raw >>>= 1;
+ }
+ return str.reverse().toString();
+ }
- /** array needed for byteToHex */
- private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
- /**
- * Converts a byte Array to a Hex String
- *
- * @param raw the byte array to convert
- * @return a hex String
- */
- public static String toHexString(byte[][] raw){
- StringBuffer ret = new StringBuffer();
-
- for(byte[] a : raw){
- for(byte b : a){
- ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
- ret.append(HEX_CHARS[(int) b & 0x0F ]);
- }
- }
+ /** array needed for byteToHex */
+ private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
+ /**
+ * Converts a byte Array to a Hex String
+ *
+ * @param raw the byte array to convert
+ * @return a hex String
+ */
+ public static String toHexString(byte[][] raw){
+ StringBuffer ret = new StringBuffer();
- return ret.toString();
- }
+ for(byte[] a : raw){
+ for(byte b : a){
+ ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
+ ret.append(HEX_CHARS[(int) b & 0x0F ]);
+ }
+ }
- public static String toHexStringByColumn(byte[][] raw){
- StringBuffer ret = new StringBuffer();
-
- for(int col=0; col>> 0x04)& 0x0F ]);
- ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]);
- }
- }
+ return ret.toString();
+ }
- return ret.toString();
- }
-
- /**
- * Converts a byte Array to a Hex String
- *
- * @param raw the byte array to convert
- * @return a hex String
- */
- public static String toHexString(byte[] raw){
- StringBuffer ret = new StringBuffer();
+ public static String toHexStringByColumn(byte[][] raw){
+ StringBuffer ret = new StringBuffer();
- for(byte b : raw){
- ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
- ret.append(HEX_CHARS[(int) b & 0x0F ]);
- }
+ for(int col=0; col>> 0x04)& 0x0F ]);
+ ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]);
+ }
+ }
- return ret.toString();
- }
+ return ret.toString();
+ }
- /**
- * Converts a byte to a Hex String
- *
- * @param raw the byte to convert
- * @return a hex String
- */
- public static String toHexString(byte raw){
- String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ];
- ret += ""+HEX_CHARS[(int) raw & 0x0F ];
+ /**
+ * Converts a byte Array to a Hex String
+ *
+ * @param raw the byte array to convert
+ * @return a hex String
+ */
+ public static String toHexString(byte[] raw){
+ StringBuffer ret = new StringBuffer();
- return ret;
- }
+ for(byte b : raw){
+ ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
+ ret.append(HEX_CHARS[(int) b & 0x0F ]);
+ }
- /**
- * Converts the given byte to a String with 1's and 0's
- *
- * @param raw the byte to convert
- * @return a String with 1's and 0's
- */
- public static String toString(byte raw){
- StringBuffer ret = new StringBuffer();
- for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){
- ret.append(( (raw & i) == 0 ? '0' : '1'));
- }
- return ret.toString();
- }
+ return ret.toString();
+ }
- /**
- * Converts the given byte array to a String with 1's and 0's
- *
- * @param raw the byte array to convert
- * @return a String with 1's and 0's
- */
- public static String toString(byte[] raw){
- StringBuffer ret = new StringBuffer();
- for(byte b : raw){
- for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){
- ret.append(( (b & i) == 0 ? '0' : '1'));
- }
- }
- return ret.toString();
- }
+ /**
+ * Converts a byte to a Hex String
+ *
+ * @param raw the byte to convert
+ * @return a hex String
+ */
+ public static String toHexString(byte raw){
+ String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ];
+ ret += ""+HEX_CHARS[(int) raw & 0x0F ];
+
+ return ret;
+ }
+
+ /**
+ * Converts the given byte to a String with 1's and 0's
+ *
+ * @param raw the byte to convert
+ * @return a String with 1's and 0's
+ */
+ public static String toString(byte raw){
+ StringBuffer ret = new StringBuffer();
+ for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){
+ ret.append(( (raw & i) == 0 ? '0' : '1'));
+ }
+ return ret.toString();
+ }
+
+ /**
+ * Converts the given byte array to a String with 1's and 0's
+ *
+ * @param raw the byte array to convert
+ * @return a String with 1's and 0's
+ */
+ public static String toString(byte[] raw){
+ StringBuffer ret = new StringBuffer();
+ for(byte b : raw){
+ for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){
+ ret.append(( (b & i) == 0 ? '0' : '1'));
+ }
+ }
+ return ret.toString();
+ }
/**
* Generates a comma separated string with key and value pairs
*
* @return a comma separated String
*/
- public static String toString(Map map){
- StringBuilder tmp = new StringBuilder();
- tmp.append("{");
- Iterator