Last active
September 15, 2019 05:39
-
-
Save altimmons/cc4ed420dd1874eb7221f823eb9d963a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generates a string the length of the argument of Random Characters from | |
* a set of given characters. Returns the String. | |
* <p> | |
* The string in the method from which characters are chosen can be edited to | |
* add characters and other special symbols. | |
* | |
* @param length - the number of Random characters to return. | |
* @return | |
*/ | |
static String randChars( int length ){ | |
int c = length; | |
if( c < 0 ) return randChars(Math.abs( c )); | |
//err handle or pass | |
// return null; | |
// throw new IllegalArgumentException(); | |
else if( length == 0 ) return ""; | |
else{ | |
//Add additional chars into the string below if needed. | |
final String allChars = "0123456789" // numerals | |
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ" //uppercase | |
+ "abcdefghijklmnopqrstuvwxyz"; //lowercase | |
// + "!@#$%^&*()" //Regular Symbols | |
// + ",.\\/<>[]{};:'\"`~=-_+ "; //all other symbols | |
char[] chArr = allChars.toCharArray(); | |
double x1 = 0.0, x2 = (double)allChars.length(); | |
StringBuilder sb = new StringBuilder(); | |
while( c > 0 ){ | |
double f = Math.random() / Math.nextDown( 1.0 ); | |
double x = x1 * ( 1.0 - f ) + x2 * f; | |
int i = (int)Math.floor( x ); | |
sb.append( chArr[ i ] ); | |
//or in a single harder to read line: | |
//sb.append( allChars.toCharArray()[(int)Math.floor(x1 * ( 1.0 - f ) + x2 * f)]); | |
c--; | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment