随机生成字符串中的字符
当用户单击按钮时,我需要在字符串java中生成随机字符。 例如:如果我们以猫为例,我需要在字符串中显示字符,如下所示:
CAT,ACT,TAC,TCA
提前致谢
阿斯旺
i need to generate random character in a String java when user click on button.
for example :if we take cat example i need to disply character in a string like follwing:
CAT,ACT,TAC,TCA
Thanks in advance
Aswan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于Fisher-Yates shuffle算法
Fisher-Yates shuffle 是一种标准算法用于洗牌。这是伪代码:
这是一个简单的 Java 实现:
然后您可以:
这将生成字符串
"stackoverflow"
(另请参阅 ideone.com)。Guava + Java Collections Framework 替代解决方案
如果您安装了 Guava 库,那么这将是一个不错的解决方案。以下是关键事实:
Chars.asList(char...)
创建一个List
实时视图 的char[]
。对返回列表的修改将影响后备数组(反之亦然)。java.util.Collections
可以shuffle(List)
然后我们可以将两者结合起来得到以下干净可读的代码
:打印
“stackoverflow”
的 10 个字谜。请注意,Guava 仅用于提供
List
char[] 的实时视图。char[]
不会自动装箱为Character[]
(反之亦然),否则Arrays.asList(T...)
就足够了。另请参阅
相关内容问题
Arrays.asList()
无法正常工作?On Fisher-Yates shuffling algorithm
Fisher-Yates shuffle is a standard algorithm for shuffling. Here's the pseudocode:
Here's a straightforward Java implementation:
Then you can have:
This will generate 10 shuffling of the string
"stackoverflow"
(see also on ideone.com).Guava + Java Collections Framework alternative solution
If you have Guava library installed, then this would be a nice solution. Here are the key facts:
Chars.asList(char...)
which creates aList<Character>
live view of achar[]
. Modifications to the returned list will affect the backing array (and vice versa).java.util.Collections
canshuffle(List<?>)
We can then combine the two to get the following clean and readable code:
The above will print 10 anagrams of
"stackoverflow"
.Note that Guava is only used to provide the
List<Character>
live view of thechar[]
. Achar[]
does not get autoboxed to aCharacter[]
(and vice versa), otherwiseArrays.asList(T...)
would've been sufficient.See also
Related questions
Arrays.asList()
not working as it should?嗨,谢谢大家,我终于找到了问题的解决方案。
Hi Thankq for all finally i got solution for my problem.