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

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.

Related

Return to beginning of a function in Swift [duplicate]

This question already has answers here:
Generate a Swift array of nonrepeating random numbers
(3 answers)
Closed 1 year ago.
So I've following code running in Xcode 12 with SwiftUI:
public func giveCard() -> String {
var randomNumber = Int.random(in: 0..<maxCards-1)
if saveRandoms.contains(randomNumber) {
print("Already exist - generate new number")
} else {
let actualCard = questionCard[randomNumber]
saveRandoms.add(randomNumber)
return actualCard
print("Schicke frage")
}
return "No question-card left"
}
The code creates random numbers between 0 and the variable maxCards.
When a questionCard fitting to the random number which was created was used, the random number is stored in the array saveRandoms.
To avoid showing the same question the if-statement checks if the new created random number is already in the array saveRandoms. If not, the fitting question will be shown.
If the number was already used it should generate a new number until finding a unused one.
And that's my problem. How can I return to the beginning of my function to check again and again if the random number was already used?
I think the best solution is to put the logic in a while loop and finish executing when a new number is found.

how can I assign the same random number to 2 variables in swift?

I am building an app that the user selects a multiplication table. Then it gives random numbers to multiplicate with the number they select. for example, if the user selects "1". the questions shown would be "1 x 1", or "1 x 8".
The problem is that I need to assign the same random number to 2 variables. The one that will be shown on the question and the one used to calculate the result.
I thought of something like this, but the random number is different on each variable. What can I do to use the same random number generated on 2 variables?
func game() -> (String, Int) {
let randomNumber = multiplicate.randomElement()
switch selectedQuestion {
case 0:
return ("1 × \(randomNumber!)", 1 * randomNumber!)
default:
return ("", 0)
}
}
Not exactly sure what you're asking but you could do something like this:
let number = Int.random(in: 0..<10)
let number2 = number
but I don't think there is a need to create a new variable for this. The whole idea of variables is that you can save some value and then use it later so there isn't really a need to create number2 here.

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
}

How to compare random numbers in Swift

I’m a beginner in programming and playing around with the arc4random_uniform() function in Swift. The program I’m making so far generates a random number from 1-10 regenerated by a UIButton. However, I want the variable ’highest' that gets initialised to the random number to update if the next generated number is larger than the one currently held in it. For example the random number is 6 which is stored in highest and if the next number is 8 highest becomes 8. I don't know how to go about this. I have connected the UIButton to an IBAction function and have the following code:
var randomValue = arc4random_uniform(11) + 1
highest = Int(randomValue)
if (Int(randomValue) < highest) {
// Don’t know what to do
}
Initialise highest to 0
Every time you generate a new random number, replace the value of highest with the higher of the two numbers
highest = max(highest, randomValue)
The max() function is part of the Swift standard library and returns the larger of the two passed in vales.
edited to add
Here's a playground showing this with a bit more detail, including casting of types:
var highest: Int = 0
func random() -> Int {
let r = arc4random_uniform(10) + 1
return Int(r)
}
var randomValue = random()
highest = max(highest, randomValue)
You can see that multiple calls persist the highest value.

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)