如何随机化字符序列?

发布于 2024-09-07 11:09:33 字数 247 浏览 2 评论 0原文

我想编写一个函数来随机化字母字符序列的顺序。例如,序列:

ABCDEFG。 。 。

...可能会更改为:

ZLTAP ...

...如果再次传递给同一函数可能会导致:

HREIC ....

有什么建议吗?

I want to write a function which randomizes the order of a sequence of alphabetic characters. For example, the sequence:

A B C D E F G . . .

...might be changed to:

Z L T A P ...

...which, if passed to the same function again could result in:

H R E I C ....

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

勿挽旧人 2024-09-14 11:09:49

你的意思是随机字母表?几天前我用 PHP 写了类似的东西。逻辑如下:

  1. 令 S1 为包含字母字符“ABC...XYZ”的字符串。
  2. 令 S2 为空字符串。
  3. 而 strlen(S1) > 0,从S1中随机选择一个字符C。将 C 添加到 S2 并从 S1 中删除 C。
  4. 返回S2。

结果是随机打乱的一组字符,以最小的 CPU 负载创建(如果字符串有 26 个字符,则内部循环只需要 26 次迭代)。

You mean randomise the alphabet? I wrote something similar in PHP a few days ago. The logic was the following:

  1. Let S1 be a string containing the alphabet characters "ABC...XYZ".
  2. Let S2 be an empty string.
  3. While strlen(S1) > 0, choose a random character C from S1. Append C to S2 and remove C from S1.
  4. Return S2.

The result is a randomly shuffled set of characters, created with minimal CPU load (if the string has 26 characters, the inner loop only needs 26 iterations).

旧时浪漫 2024-09-14 11:09:46

这听起来像是家庭作业,但无论如何:

http://stanford.edu/~blp /writings/clc/shuffle.html

This sounds like homework, but either way:

http://stanford.edu/~blp/writings/clc/shuffle.html

浮生面具三千个 2024-09-14 11:09:43

查看 Fisher-Yates shuffle 算法,特别是 现代版本

Have a look at the Fisher-Yates shuffle algorithm, and in particular the modern version of it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文