in cases where I really need really really random sequence of characters(in this case alphabets)
Strictly for programmers who have used random api in any programming language, stictly programmers because
every one of us know that the machine really doesn't generate a random entity that we need.
In languages at least like java, c, that I have real experience with. The random generation was only at the first run
and repeatition of the same on the subsequent runs.
Here is one technique in java that I have used to create a really random sequence of alphabets on all subsequent run of the code.
/**
* @author nsingh
*
*/
public class RandomKeyFunctionality {
public static void main(String args[]) {
String str = randomKeyFunctionality();
System.out.println(str);
}
private static String randomKeyFunctionality() {
int count = 13;
StringBuffer sb =new StringBuffer();
while (sb.toString().length() < count) {
randomValue(sb);
}
return sb.substring(0, count);
}
/**
* Generates the input string randomly. Calls the getValue() for getting the
* index, pass into the digits array, gets the character,append to the sting
* and returns output string.
* @param sb
* @return
*/
private static String randomValue(StringBuffer sb) {
char[] digits = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z' };
double valueDouble = Math.random();
Double d =new Double(valueDouble * 100000);
// System.out.println(d.toString(d));
Integer inputObj =new Integer(d.intValue());
System.out.println(d.intValue());
RandomInputOutput random =new RandomInputOutput(0, inputObj.intValue());
System.out.println(inputObj.intValue());
while (random.input > 0) {
getValue(random);
sb.append(digits[random.result]);
}
return sb.toString();
}
private static void getValue(RandomInputOutput value) {
int temp1, temp2;
temp1 = value.input % 10;
temp2 = value.input / 10;
value.input = temp2;
value.result = temp1;
}
}
class RandomInputOutput {
int result;
int input;
public RandomInputOutput(int result, int input) {
this.result = result;
this.input = input;
}
}
Happy Coding, Thanks for stopping by and thanks for reading!!
~Nirmal
Anything that won't sell, I don't want to invent. Its sale is proof of utility, and utility is success.
Thomas A. Edison
No comments:
Post a Comment