Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

objective c - Generate non-repeating, no sequential numbers

how does one use code to do this:

produce 15 random numbers [EDIT: from 1 - 15] 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

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest way is to produce a collection (e.g. an array) of the numbers 1-15, and then shuffle it. (EDIT: 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 :)

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;
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...