随机生成特定范围内的整数序列

发布于 2024-08-27 23:00:32 字数 245 浏览 4 评论 0原文

我不确定如何表达,而且我的数学能力也不是那么强。但这就是我需要的。

我想生成所有 16 位整数 (0-65535) 的列表。但每次这样做时,我都想随机播种算法,每次列表都以不同的整数开头,并且所有后续整数都将生成一次,但也是以随机顺序生成。

小例子(1-5):...

1, 5, 3, 2, 4

4, 3, 1, 5, 2

2, 1, 4, 5, 3 ...

有什么帮助吗?

I am unsure how to put this and my math skills aren't that strong. But here's what I need.

I want to generate a list of all the 16bit integers (0-65535). But everytime I do so I want to seed the algorithm randomly that each time the list starts with a different integer and all the subsequent integers will be generated once but also in random order.

small example (1-5): ...

1, 5, 3, 2, 4

4, 3, 1, 5, 2

2, 1, 4, 5, 3 ...

Any help?

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

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

发布评论

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

评论(3

樱花细雨 2024-09-03 23:00:32

最简单的方法可能是生成所需数字的列表 然后对其进行洗牌

The easiest way is probably to generate the list of required numbers and then shuffle it.

爱本泡沫多脆弱 2024-09-03 23:00:32

假设您没有安全要求,最简单的方法可能是创建一个线性同余生成器 (LCG) 并在每次需要更改序列时选择新的乘数和/或增量。使用维基百科条目中的表示法,如果您想要所有 k 位整数,则模数为 m=2k,条件 1、2 和 3 简化为:
1. c 是奇数
2. 对于任意整数 x,a = 1 + 4*x

还有其他类似于 LCG 的生成器,应该同样令人满意。

Assuming you have no security requirements, possibly the easiest method is to create a Linear Congruential Generator (LCG) and select a new multiplier and/or increment every time you need to change the sequence. Using the notation from the Wikipedia entry, if you want all k-bit integers, your modulus is m=2k and conditions 1, 2, and 3 simplify to:
1. c is odd
2. a = 1 + 4*x for any integer x

There are other generators that are similar to LCG that should be just as satisfactory.

来世叙缘 2024-09-03 23:00:32
  1. 创建一个整数列表。在您的示例中,从 1 到 5(含);
  2. 对它进行正确的洗牌。例如,Fisher-Yates 洗牌。 “正确”部分很重要,因为不正确的洗牌算法会产生有偏差的结果。

你没有说你使用什么语言,但这里有两种:

PHP

$arr = range(1, 5);
shuffle($arr);

Java

List<Integer> list = new ArrayList<Integer>();
for (int i=1; i<=5; i++) {
  list.add(i);
}
Collections.shuffle(list);
  1. Create a list of integers. In your example from 1 to 5 inclusive;
  2. Perform a correct shuffle on it. For example, the Fisher-Yates shuffle. The "correct" part is important as an incorrect shuffle algorithm will yield biased results.

You don't say what language you use but here are two:

PHP

$arr = range(1, 5);
shuffle($arr);

Java

List<Integer> list = new ArrayList<Integer>();
for (int i=1; i<=5; i++) {
  list.add(i);
}
Collections.shuffle(list);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文