// // String Random by Words // public class randomWords { static final int MAXWORDS = 512; /* Permutation list variables */ static final int MAXPERMLIST = 120; static int setperm_listlen = 0; static int setperm_cur = 0; static int setperm_list[] = new int[MAXPERMLIST]; public static String toString(String source) { int i; // Walk through the string, picking out words and // storing them for later regurgitation in a random order. char whiteSpace = ' '; int startLoc = 0; int wsLoc = 1; String words[] = new String[MAXWORDS]; int numWords = 0; String newString = ""; while (wsLoc > 0) { wsLoc = source.indexOf(whiteSpace, startLoc); if (wsLoc < 0) { words[numWords++] = source.substring(startLoc); if (numWords == MAXWORDS) { System.out.println("randomWords: too many words in string!"); break; } break; } words[numWords++] = source.substring(startLoc, wsLoc); startLoc = wsLoc+1; } if (numWords == 0) { return ""; } // Create a permutation of numbers between 1 .. numWords setperm(numWords); // Build a new string by selecting random elements from the // above permutation list. for (i = 0; i < numWords-1; i++) { newString += words[randp()-1] + " "; } newString += words[randp()-1]; return newString; } static void setperm(int range) { int i, j, val; boolean not_done, unique; /* Create a set of random numbers between 1 .. *range* */ if (range < 1) return; setperm_listlen = 0; setperm_cur = 0; /* first element to "randp" out */ for (i = 0; i < range; i++) { not_done = true; val = 1; /* shut the compiler up */ while (not_done) { /* find a new unique number between 1 .. range */ val = (int) (Math.random() * (double) range); val++; unique = true; for (j = 0; j < setperm_listlen; j++) { if (setperm_list[j] == val) { unique = false; break; } } if (unique) not_done = false; } setperm_listlen = i+1; setperm_list[i] = val; } } static int randp() { /* Return the next element of the *setperm* list */ if (setperm_cur < setperm_listlen) return(setperm_list[setperm_cur++]); return(0); } }