How can I make various strings and shuffle them randomly - swift

#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())

Related

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.

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 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

Using a random number to select a variable

I have two variables, string0 and string1. I want to randomly set a label to one of those strings. I tried generating the variable name using a random number like this:
let string0a = "\(Name!) sees something that offends \(Gender!)."
let string1a = "\(Name!) saw Star Wars earlier."
let number = arc4random_uniform(1)
text1.text = string\(number!)a
What is the best way to randomly set the label text to one of the two strings?
You can't generate variable names at runtime in Swift because they are used at compile time. This is what arrays were invented for:
let strings = [string0a, string1a]
let number = Int(arc4random_uniform(2))
text1.text = strings[number]
or more concisely:
text1.text = [string0a, string1a][Int(arc4random_uniform(2))]

cannot invoke avgArray with an argument list of int

I'm new to Swift, and just start to learn this language by following The Swift Programming Language. In this book, there is an exercise question that ask me to write a function to calculate the average of an array. Here is my code:
func avgArray(elements: Int...)->Double{
var avg:Double = 0
var sum = 0
var count = 0
for element in elements {
sum += element
count += 1
}
avg = Double(sum) / Double(count)
return avg
}
let numberlist = [2,3,6,7,2,7,0,9,12]
let average = avgArray(numberlist)
I don't know why I can't pass the array into my function. Also, is there a way besides using a count variable to keep track of the number of elements in the array?
I don't know why I can't pass the array into my function.
Your elements is not an array, it is a variadic parameter. Change it to
func avgArray(elements: [Int])->Double{
and you should be good to go.
is there a way besides using a count variable to keep track of the
number of elements in the array?
Absolutely. count property of the array itself. You can use it in your code like this:
avg = Double(sum) / Double(elements.count)