Is there a way to randomly generate numbers, that won't repeat, in Swift?
Asked
Active
Viewed 1,358 times
-5
-
4It would be surprising if there isn't. You need to clarify your question. What *sorts* of numbers? How many? What have you tried to do? – John Coleman Jan 09 '17 at 12:52
-
1GameplayKit has various random number generators, e.g. [GKShuffledDistribution](https://developer.apple.com/reference/gameplaykit/gkshuffleddistribution) *"... where short sequences of similar values are unlikely."* – "Shuffling" an array can be another option: http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift. – Martin R Jan 09 '17 at 12:59
-
Please post code. You are probably using a seeded random number algorithm, that you did not seed. – shallowThought Jan 09 '17 at 13:06
-
1Possible duplicate of [Unique (non-repeating) random numbers in O(1)?](http://stackoverflow.com/questions/196017/unique-non-repeating-random-numbers-in-o1) – Mr. Xcoder Jan 09 '17 at 13:06
-
@JohnColeman I am creating a quiz app, I needed to generate a random number between 0 and 18 to correspond to questions in an array, however I couldn't manage to do so without the number generated being repeated, hence the need for a way to generate non repeating numbers. – whutson Jan 09 '17 at 17:26
-
@JohnColeman I've tried removing the corresponding question from the array once the number is generated so that it is not selected again, and then reducing the possible numbers being selected from by 1 each time. This worked, however created a whole new set of problems that I don't think will be resolvable using this method. – whutson Jan 09 '17 at 17:31
2 Answers
1
How does one generate a random number in Apple's Swift language?
check this answer, you can then write an easy function to check your array or data structure for duplicate numbers.

Community
- 1
- 1

Kostas Tsoleridis
- 926
- 7
- 13
0
Yes. But it's not really Swift, it's a framework:
Specifically, it's got wonderful randomisation features, one of which does exactly what you're (probably) wanting, shuffling. It's called "shuffling" cause it's kind of like when you shuffle a set of cards, and then deal them out from the deck:
https://developer.apple.com/reference/gameplaykit/gkshuffleddistribution