使用 Java 打乱单词
我想打乱一个字符串,使其不可读,所以想出了这个方法:
public String scrambleWord(String start_word){
char[] wordarray = start_word.toCharArray();
char[] dummywordarray = start_word.toCharArray();
Random random = new Random();
int r = random.nextInt(wordarray.length-1);
int i = 0;
int j = r+1;
while(i <= r){
dummywordarray[wordarray.length -i-1] = wordarray[i];
i++;
}
while (j <= wordarray.length -1){
dummywordarray[j-r-1] = wordarray[j];
j++;
}
String newword = String.valueOf(dummywa);
return newword;
所以我首先将字符串转换为字符数组,在我的方法中,我必须复制字符数组“dummywordarray”。通过该算法一次,单词的每个字母都会改变位置。但它不会被很好地打乱,从某种意义上说,你可以一眼就把它重新组合在一起。 所以我通过该方法传递了一个少于 9 个字符的给定字符串 7 次,并且这些单词相当混乱,即不可读。 但我用 30 个字符的字符串进行了尝试,花了 500 遍才保证它被很好地打乱。 500! 我确信有更好的算法,我想要一些建议 a) 改进该方法 或者 b) 更好的方法。
I wanted to scramble a String, to make it unreadable and so came up with this method:
public String scrambleWord(String start_word){
char[] wordarray = start_word.toCharArray();
char[] dummywordarray = start_word.toCharArray();
Random random = new Random();
int r = random.nextInt(wordarray.length-1);
int i = 0;
int j = r+1;
while(i <= r){
dummywordarray[wordarray.length -i-1] = wordarray[i];
i++;
}
while (j <= wordarray.length -1){
dummywordarray[j-r-1] = wordarray[j];
j++;
}
String newword = String.valueOf(dummywa);
return newword;
SO I first converted the string to a char array, and in my method I had to duplicate the char array "dummywordarray". Passing once through this algorithm every lette rof the word will have changed position. But it wont be scrambled very well, in the sense that you could put it back together at a glance.
SO I passed a given String of less than 9 characters through the method 7 times, and the words are fairly well scrambled, i.e. unreadable.
But I tried it with a 30 character string and it took 500 passes before I could guarantee it was nicely scrambled. 500!
I'm sure there is a better algorithm, I'd like some advice on either
a)improving this method
or
b)a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
换句话说
,您可以利用现有的
java.util.Collections.shuffle(List)
方法。不幸的是,您必须跳过几个环节才能使用它,因为您不能在泛型中使用基元。编辑:
shuffle
工作的基本方式(有关完整说明,请参阅 Javadoc)如下所示:编辑 2:
这种方法与 Guava 的
Chars
实用程序:How about
In other words, you could take advantage of the existing
java.util.Collections.shuffle(List)
method. Unfortunately you have to jump through a couple of hoops to use it, since you can't use primitives in Generics.Edit:
The basic way that
shuffle
works (see the Javadoc for the full explanation), is like this:Edit 2:
This approach is significantly less verbose with Guava's
Chars
utilities: