生成非重复,无序列号 [英] Generate non-repeating, no sequential numbers

查看:103
本文介绍了生成非重复,无序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用代码执行此操作:

how does one use code to do this:

生成15个随机数,这些数字不是任何顺序,只发生一次
例如。

produce 15 random numbers that are not in any order, and that only occur once eg.

1 4,2,5,3,6,8,7,9,10,13,12,15,14,11

1 4, 2, 5, 3, 6, 8, 7, 9, 10, 13, 12, 15, 14, 11

rand()或arc4rand()可以重复一些,这不是我之后的事情。

rand() or arc4rand() can repeat some, which is not what im after.

谢谢

推荐答案

最简单的方法是制作一个集合(例如数字1-15的数组,然后将其洗牌。 (编辑:通过数字1-15的集合,我的意思是1,2,3,4,5 ...... 15.不是 1-15范围内的随机数的集合。如果我的意思是,我已经这么说了:))

The simplest way is to produce a collection (e.g. an array) of the numbers 1-15, and then shuffle it. ( By "collection of the numbers 1-15" I mean 1, 2, 3, 4, 5... 15. Not a collection of random numbers in the range 1-15. If I'd meant that, I'd have said so :)

您还没有详细说明您所在的平台,因此我们无法轻松提供样品代码,但我是 Fisher-Yates的现代版本的忠实粉丝洗牌。例如,在C#中:

You haven't given details of which platform you're on so we can't easily give sample code, but I'm a big fan of the modern variant of the Fisher-Yates shuffle. For example, in C#:

public static void Shuffle<T>(IList<T> collection, Random rng)
{
    for (int i = collection.Count - 1; i > 0; i--)
    {
        int randomIndex = rng.Next(i + 1);
        T tmp = collection[i];
        collection[i] = collection[randomIndex];
        collection[randomIndex] = tmp;
    }
}

如果你想产生更随机的数字(例如,整个可用整数范围内有15个不同的整数)那么可能最容易做这样的事情(再次,C#但应该很容易移植):

If you want to produce "more random" numbers (e.g. 15 distinct integers within the entire range of integers available to you) then it's probably easiest just to do something like this (again, C# but should be easy to port):

HashSet<int> numbers = new HashSet<int>();
while (numbers.Count < 15)
{
    numbers.Add(rng.Next());
}
List<int> list = numbers.ToList();
// Now shuffle as before

最后洗牌是为了确保任何可能从集合实现中排序的顺序不会影响最终结果。

The shuffling at the end is to make sure that any ordering which might come out of the set implementation doesn't affect the final result.

这篇关于生成非重复,无序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆