Showing posts with label random. Show all posts
Showing posts with label random. Show all posts

Wednesday, 22 June 2011

Generating random unique strings with JAVA

Method1
If you need randomly generated Strings in your java code you can use the below functions. This function is using SecureRandom class to get its work done.
public String generateRandomString(String s) {
try {
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
String randomNum = new Integer(prng.nextInt()).toString();
randomNum += s;
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest(randomNum.getBytes());
return hexEncode(result);
} catch (NoSuchAlgorithmException e) {
return System.currentTimeMillis()+"_"+username;
}
}

The classical hexEncode method:
protected String hexEncode(byte[] aInput) {
StringBuffer result = new StringBuffer();
char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
for (int idx = 0; idx < aInput.length; ++idx) {
byte b = aInput[idx];
result.append(digits[(b & 0xf0) >> 4]);
result.append(digits[b & 0x0f]);
}
return result.toString();
}

Suppose that you need to generate unique random session ids for your logged in users. You can use the above function as follows :
String sessionId = generateRandomString(username);

Method 2 : Using Long.toHesString()
Long.toHexString(Double.doubleToLongBits(Math.random()));

Just use simple String of numbers and alphabets to get Random string of desired length:
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rnd = new Random();

String randomString( int len )
{
StringBuilder sb = new StringBuilder( len );
for( int i = 0; i < len; i++ )
sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
return sb.toString();
}


Method 3

Apache classes also provide ways to generate random string using org.apache.commons.lang.RandomStringUtils (commons-lang).



Wednesday, 15 September 2010

Random in java

The expression Math.random() yields a random double number in the range zero (0.0) to one (1.0) (excluding the upper limit of exactly 1.0). You can print this value using: 
double rand = Math.random();
System.out.println(""+rand);
You can convert this to an integer in the range 1 to n using the  following code where n = 10

int n = (int)(Math.random()*10)+1;
System.out.println(""+n);