Return to beginning of a function in Swift [duplicate] - swift

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.

Related

Swift store all numbers that are random generated and won't generated them again

I am trying to store all numbers that the random number generator generate. After that the number generator needs to check if the number already was generated and if so it will keep generate a new number until all number for example 1 to 30 are generated. I have so far only the random number generator:
if let Aantalvragen = snapshot?.data()!["Aantal vragen"] as? String {
self.AantalVragenDef = Aantalvragen
}
let RandomVraag = Int(arc4random_uniform(UInt32(self.AantalVragenDef)!) + 1)
AantalVragenDef is an number that indicates how many questions there are. So the generator knows how far it can generate. Please help.
The easiest is probably to create an array or list and fill it with the numbers 1 to n that you want, shuffle it and then use the numbers in the order they appear. That way you are guaranteed that each number show up exactly once.
See how to shuffle an array in Swift
I believe what you are trying to get is a random generator that generates numbers from 1 to the number of questions, but if the number already exists, you don't want to keep it. I suggest using if-else statements and arrays.
The code might look something like this:
if let Aantalvragen = snapshot?.data()!["Aantal vragen"] as? String {
self.AantalVragenDef = Aantalvragen
}
var array = [Int]()
while array.count != self.AantalVragenDef {
let RandomVraag = Int(arc4random_uniform(UInt32(self.AantalVragenDef)!) + 1)
if array.contains(RandomVraag) == false {
array.append(RandomVraag)
}
}
This loop will continue until there are (number of questions) integers in the array. Let me know if this is what you are looking for.
Good Luck, Arnav

Swift 4: modifying numbers in String [duplicate]

This question already has answers here:
Leading zeros for Int in Swift
(12 answers)
Closed 5 years ago.
In my application i create multiple files and i would like them to have consecutive numbering as part of the name. For example log_0001, log_0002
I use string interpolation, so in code it looks like
fileName = "log_\(number)"
number = number + 1
However, if i keep number as just Int, i will have log_1 instead of log_0001
I've only figured that i could check if number has 1/2/3/4 digits and add '000/00/0' manually.
Are there any String modifications allowing to put the required number of '0' to make it 4 symbols?
"I've only figured that i could check if number has 1/2/3/4 digits and add '000/00/0' manually."
In this case try the following code: Save the digit length in a variable, for example digitLength.
if (digitLength == 1) { print("log_000")
} else if (digitLength == 2) { print("log_00")
} else if (digitLength == 3) { print("log_0")
}
else { print("log_") }
print(number)
and then the variable.

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)

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.