Originally Posted by
JonnySKK
I need to generate a random replacement for each character
I would use a "random shuffle algorithm" to create a character array that has a "random" replacement for each character in the original [A-Z] array.
Here's a testbed:
import java.util.*;
public class Z {
public static void main(String [] args) {
char [] plain = new char[26];
char thisChar = 'A';
for (int i = 0; i < 26; i++) {
plain[i] = thisChar++;
}
System.out.printf("Plain :");
printArray(plain);
char [] enc = Arrays.copyOf(plain, plain.length);
randomShuffle(enc);
System.out.printf("Encode Key :");
printArray(enc);
} // End main()
static void printArray(char [] x) {
System.out.print("[");
for (int i = 0; i < x.length; i++) {
System.out.printf("%c", (char)x[i]);
}
System.out.println("]");
}
static void randomShuffle(char [] x) {
//
// Suggestion: Use "The modern algorithm" pseudo-code from
//the wikipedia article "Fisher-Yates shuffle"
//
}
}
Not familiar with 'random shuffle'?
See "The Modern Algorithm" pseudo-code at
Fisher-Yates shuffle - wikipedia
It translates to about five or six lines of Java. It's really simple, very efficient (requires a grand total of 25 values from a "random" number generator), and it is mathematically robust, as indicated in the wikipedia article and in Volume 2 (Seminumerical Algorithms) of Knuth's
The Art of Computer Programming.
A run or two or three:
Plain :[ABCDEFGHIJKLMNOPQRSTUVWXYZ]
Encode Key :[SFVXGTAPEDNUCBLIJOKWHYRQZM]
And
Plain :[ABCDEFGHIJKLMNOPQRSTUVWXYZ]
Encode Key :[CEANDLIWRZFGKMQPTBJUXHOSVY]
And
Plain :[ABCDEFGHIJKLMNOPQRSTUVWXYZ]
Encode Key :[OPAYZGJTSRFUWQLHIKCMDNBEVX]
I could go on all day...
Cheers!
Z