how can I assign the same random number to 2 variables in swift? - 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.

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: how to change a integer variable name within a method and reassign its value

I am a complete beginner at Swift/programming and am making a noughts and crosses app as part of an online course. I wanted to do this on my own before I saw the solution so my logic may be a bit weird.
I have a function which is called each time a button is pressed (there are 9, one for each square). The function acts to:
i) update the number of turns (which allows me to see who's go it is)
ii) change the picture to X or O
iii) deactivate the button after each turn
iv) calculate is anyone has won by changing the value of that squares potential lines. The numbers I have chosen to do this are 3 and 4 (for noughts and crosses), hence the c = 3 or 4 below. This means that if any winning line adds up to 9 or 12, the game stops as someone has won.
I have 9 variables (Int) that hold the score for each square - they are a1o, a2o, a3o, b1o... i.e all end in "o". In the function I want to add the string of "a1" in front of the "o", meaning each button is only relevant to itself with only one line of code above the function (within the button parentheses).
The function looks like this at the moment; calling it by: button(a1, buttonValue: "a1")
func button(buttonName: UIButton, buttonValue: NSString) -> String {
let a = buttonName
var b = buttonValue
b = (b as String) + "o"
print(b)
// the above prints "a1o", the name of the variable, but it is a string...
index += 1
print("Go number \(index)")
if index % 2 == 0 {
// show a nought
a.setImage(UIImage(named: "nought.png"), forState: UIControlState.Normal)
c = 3
// the above line doesn't work as its a string, but I am attempting to set the squares value to 3 (i.e. a1o = 3)
winner()
a.userInteractionEnabled = false
} else {
// show a cross
a.setImage(UIImage(named: "cross.png"), forState: UIControlState.Normal)
c = 4
// the above line doesn't work as its a string
winner()
a.userInteractionEnabled = false
}
return "done"
}
What I can't figure out is how to change the common stem of the variable *a1*o by not making it a string, or if I do, how I convert it back to a variable.
I am struggling with definitions and as a result looking for an answer has been hard. The variable a1o is an integer, but how do I refer to a1o itself?
Thank you in advance,
Sam
It is not possible to access variables dynamically by name like you want to do. However, there are better ways to accomplish the same goal. How about a two-dimensional array?
var scores: [[Int]] = [[0,0,0], [0,0,0], [0,0,0]]
scores[0][1] = 4 //this is the new version of "a2o = 4"
Unlike with variable names, the indices to the array ("0" and "1" in this case) can be dynamically chosen. Or, if you really want to keep your buttons' values exactly the same, you could use a dictionary:
var scores: [String: Int] = [:]
scores[buttonValue as String] = 4

How do I generate a random number not including one without using a while loop?

Let's say I want to generate a random number between 1 and 100, but I don't want to include 42. How would I do this without repeating the random method until it is not 42.
Updated for Swift 5.1
Excluding 1 value
var nums = [Int](1...100)
nums.remove(at: 42)
let random = Int(arc4random_uniform(UInt32(nums.count)))
print(nums[random])
Excluding multiple values
This extension of Range does provide a solution when you want to exclude more than 1 value.
extension ClosedRange where Element: Hashable {
func random(without excluded:[Element]) -> Element {
let valid = Set(self).subtracting(Set(excluded))
let random = Int(arc4random_uniform(UInt32(valid.count)))
return Array(valid)[random]
}
}
Example
(1...100).random(without: [40,50,60])
I believe the computation complexity of this second solution is O(n) where n is the number of elements included in the range.
The assumption here is the no more than n excluded values are provided by the caller.
appzYourLife has some great general purpose solutions, but I want to tackle the specific problem in a lightweight way.
Both of these approaches work roughly the same way: Narrow the range to the random number generator to remove the impossible answer (99 answers instead of 100), then map the result so it isn't the illegal value.
Neither approach increases the probability of an outcome relative to another outcome. That is, assuming your random number function is perfectly random the result will still be random (and no 2x chance of 43 relative to 5, for instance).
Approach 1: Addition.
Get a random number from 1 to 99. If it's greater than or equal to the number you want to avoid, add one to it.
func approach1()->Int {
var number = Int(arc4random_uniform(99)+1)
if number >= 42 {
number = number + 1
}
return number
}
As an example, trying to generate a random number from 1-5 that's not 3, take a random number from 1 to 4 and add one if it's greater than or equal to 3.
rand(1..4) produces 1, +0, = 1
rand(1..4) produces 2, +0, = 2
rand(1..4) produces 3, +1, = 4
rand(1..4) produces 4, +1, = 5
Approach 2: Avoidance.
Another simple way would be to get a number from 1 to 99. If it's exactly equal to the number you're trying to avoid, make it 100 instead.
func approach2()->Int {
var number = Int(arc4random_uniform(99)+1)
if number == 42 {
number = 100
}
return number
}
Using this algorithm and narrowing the range to 1-5 (while avoiding 3) again, we get these possible outcomes:
rand(1..4) produces 1; allowed, so Result = 1
rand(1..4) produces 2, allowed, so Result = 2
rand(1..4) produces 3; not allowed, so Result = 5
rand(1..4) produces 4, allowed, so Result = 4

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.

How can I make various strings and shuffle them randomly

#IBAction func buttonTapped() {
//I figured out how to put random numbers but I want to put random words that I write
var randomText = String(arc4random_uniform(5))
textLabel.setText(randomText)
}
Basically instead of having random numbers being displayed when button is tapped, I want random strings to display. For example ["yes", "no", maybe"] randomly appearing instead of numbers 0-5.
How would I do this?
You should create an array of all of the strings you want to possibly display, then generate a random number between 0 and the array count (minus 1 for the index), then use that random number to get a string from the array.
func getRandomString()->String{
let sArray = ["Yes","No","Maybe","Like","Ok"] //can have any number of words
let count = UInt32(sArray.count)
let randNumber = Int(arc4random_uniform(count))
return sArray[randNumber]
}
println(getRandomString())