How to generate random numbers without repetition in Swift? [duplicate] - swift

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
How do I shuffle an array in Swift?
(25 answers)
Closed 8 years ago.
How can I generate random numbers between 0 and 31 without call the number twice in Swift Language ?

You can create a function that returns a random-number generating closure, like this:
func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
var numbers: [Int] = []
return {
if numbers.isEmpty {
numbers = Array(min ... max)
}
let index = Int(arc4random_uniform(UInt32(numbers.count)))
return numbers.remove(at: index)
}
}
To use it, first call the generator once to create the random sequence generator, then call the return value as many times as you like. This will print out random values between one and six, cycling through all of them before starting over:
let getRandom = randomSequenceGenerator(min: 1, max: 6)
for _ in 1...20 {
print(getRandom())
}

Related

How can I return a combined Int from an [Int] array? [duplicate]

This question already has answers here:
Concatenate Swift Array of Int to create a new Int
(5 answers)
Closed 2 years ago.
I have an [Int] array like so:
[1, 2, 3]
How can I apply a function on this so it returns:
123
?
let nums = [1, 2, 3]
let combined = nums.reduce(0) { ($0*10) + $1 }
print(combined)
Caveats
Make sure the Int won't overflow if the number gets too long (+263 on a 64-bit system).
You need to also be careful all numbers in the list aren't more than 9 (a single base-10 digit), or this arithmetic will fail. Use the String concatenation technique to ensure that all base-10 numbers are correctly handled. But, again, you need to be careful that the number won't overflow if you choose to convert it back to an Int.
We can do like below...
var finalStr = ""
[1,2,3].forEach {
finalStr.append(String($0))
}
if let number = Int(finalStr) {
print(number)
}

I seem to have an infinite while loop in my Swift code and I can't figure out why

var array: [Int] = []
//Here I make an array to try to dictate when to perform an IBaction.
func random() -> Int {
let rand = arc4random_uniform(52)*10+10
return Int(rand)
}
//this function makes a random integer for me
func finalRand() -> Int {
var num = random()
while (array.contains(num) == true){
if (num == 520){
num = 10
}else {
num += 10
}
}
array.append(num)
return num
}
The logic in the while statement is somewhat confusing, but you could try this:
var array:Array<Int> = []
func finalRand() -> Int {
var num = Int(arc4random_uniform(52)*10+10)
while array.contains(num) {
num = Int(arc4random_uniform(52)*10+10)
}
array.append(num)
return num
}
This way there will never be a repeat, and you have less boiler code.
There is probably a better method involving Sets, but I'm sorry I do not know much about that.
A few things:
Once your array has all 52 values, an attempt to add the 53rd number will end up in an infinite loop because all 52 values are already in your array.
In contemporary Swift versions, you can simplify your random routine to
func random() -> Int {
return Int.random(in: 1...52) * 10
}
It seems like you might want a shuffled array of your 52 different values, which you can reduce to:
let array = Array(1...52).map { $0 * 10 }
.shuffled()
Just iterate through that shuffled array of values.
If you really need to continue generating numbers when you’re done going through all of the values, you could, for example, reshuffle the array and start from the beginning of the newly shuffled array.
As an aside, your routine will not generate truly random sequence. For example, let’s imagine that your code just happened to populate the values 10 through 500, with only 510 and 520 being the final possible remaining values: Your routine is 51 times as likely to generate 510 over 520 for the next value. You want to do a Fisher-Yates shuffle, like the built-in shuffled routine does, to generate a truly evenly distributed series of values. Just generate array of possible values and shuffle it.

Swift 3 - Make a Random number generate in between 2 integer variables [duplicate]

This question already has answers here:
How does one make random number between range for arc4random_uniform()?
(18 answers)
Closed 5 years ago.
i'm semi new to xcode and swift, and i'm just making some small apps to play around with some stuff. I wanted to try and make a number generator in which you set the minimum number and maximum number and the app will pick a random number in between the two. Would this be possible?
I all that I need help with is making a random number appear in between two variable integers just to clarify.
Thanks
Swift 4.2 Edit:
func randomBetween(min: Int, max: Int) -> Int {
return Int.random(in: min ..< max)
}
import GameKit
func randomBetween(min: Int, max: Int) -> Int {
return GKRandomSource.sharedRandom().nextInt(upperBound: max - min) + min
}

Generate a random number in swift and then add another number to it? [duplicate]

This question already has answers here:
How to generate a random number in Swift?
(26 answers)
Closed 7 years ago.
How do I generate a random number in Swift language that can be used in math, such as addition. Basically I just want to be able to generate a random number and then add it to a count that I have.
For example, how would I generate a random number that I can add 1 to?
Use arc4random_uniform() function because it generates a uniform distribution.
The following line generates a number from 0-9.
var x = Int(arc4random_uniform(10)) // Cast it to Int because function returns UInt32
println(x)
var sum = 10 + x
println(sum)
Try to use this one & the arc4random function will generate value between 1-9 & it returns UInt32 type value so modify it what you wanna.
var count : UInt32 = 10
var value : UInt32 = arc4random()%10
count += value
print(count)

How do you generate a random number in swift? [duplicate]

This question already has answers here:
How to generate a random number in Swift?
(26 answers)
Closed 8 years ago.
tl:dr; How do I generate a random number, because the method in the book picks the same numbers every time.
This seems to be the way in Swift to generate a random number, based on the book released from Apple.
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
for _ in 1..10 {
// Generate "random" number from 1-10
println(Int(generator.random() * 10)+1)
}
The problem is that in that for loop I put at the bottom, the output looks like this:
4
8
7
8
6
2
6
4
1
The output is the same every time, no matter how many times I run it.
The random number generator you created is not truly random, it's psueodorandom.
With a psuedorandom random number generator, the sequence depends on the seed. Change the seed, you change the sequence.
One common usage is to set the seed as the current time, which usually makes it random enough.
You can also use the standard libraries: arc4random(). Don't forget to import Foundation.
Pseudorandom number generators need a "seed" value. In your case, if you change lastRandom with any number, you'll get a different sequence.