Swift 4 - Quiz App Random Questions
First you need to store the array of random questions that you generate (side note you appear to try to generate 10 random numbers but have only 5 questions).
Then instead of using the currentQuestion directly you use that to access the question in the array.
So change it to this:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
questionArray = generateRandomNumber(0, 9, 10)
}
override func viewDidAppear(_ animated: Bool) {
newQuestion()
}
// Quiz//
let questions = ["Q1","Q2","Q3","Q4","Q5"]
let answers = [["A","2","3"],["B","2","3"],["C","2","3"],["D","2","3"],["E","2","3"]]
//Variables
var currentQuestion = 0
var rightAnswerPlacement:UInt32 = 0
var questionArray: [Int] = [] // Just an initial value
//Generate Random Numbers
func generateRandomNumber(_ from:Int, _ to:Int, _ qut:Int?) -> [Int] {
var myRandomNumbers = [Int]() //All our generated numbers
var numberOfNumbers = qut //How many numbers to generate
let lower = UInt32(from) //Generate from this number..
let higher = UInt32(to+1) //To this one
if numberOfNumbers == nil || numberOfNumbers! > (to-from) + 1 {
numberOfNumbers = (to-from) + 1
}
while myRandomNumbers.count != numberOfNumbers {
let myNumber = arc4random_uniform(higher - lower) + lower
if !myRandomNumbers.contains(Int(myNumber)) {
myRandomNumbers.append(Int(myNumber))
}
}
return myRandomNumbers
}
//Label
@IBOutlet weak var lbl: UILabel!
//Button
@IBAction func action(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerPlacement)) {
print ("RIGHT!")
} else {
print ("WRONG!!!!!!")
}
if (currentQuestion != questions.count) {
newQuestion()
} else {
}
}
//Function that displays new question
func newQuestion() {
lbl.text = questions[questionArray[currentQuestion]]
rightAnswerPlacement = arc4random_uniform(3)+1
//Create a button
var button:UIButton = UIButton()
var x = 1
for i in 1...3 {
//Create a button
button = view.viewWithTag(i) as! UIButton
if (i == Int(rightAnswerPlacement)) {
button.setTitle(answers[questionArray[currentQuestion]][0], for: .normal)
} else {
button.setTitle(answers[questionArray[currentQuestion]][x], for: .normal)
x = 2
}
}
currentQuestion += 1
}
(I think the code is correct but I'm currently running some tests in Xcode so can't check. If there is a problem leave a comment.)
Shuffle/Randomize Questions from an Array with no Repetition (SWIFT)
You seem to be shuffling the list
every time you call updateQuestion
which seems to be the issue here. You are only supposed to call the shuffle
once and iterate through the questions one by one. To fix the issue remove the shuffle from updateQuestion
and add it in viewDidLoad
or just call it once in updateQuestion
based on a condition like this:
if questionNumber == 1 {
allQuestions.list.shuffle()
}
Wanting to generate a random maths function using swift?
One way to do this is to correspond a number with each operator:
let operator = Int.random(in: 0..<4)
let number1 = Int.random(in: 0..<10)
let number2 = Int.random(in: 0..<10)
switch operator {
case 0: question = "\(number1) + \(number2)"
case 1: question = "\(number1) - \(number2)"
case 2: question = "\(number1) / \(number2)"
case 3: question = "\(number1) * \(number2)"
}
Seeing that this is intended for little kids, you can be a little smart when you generate questions. Using a simple approach like the above might result in questions like "5 / 3" which might confuse some kids who does not know about decimal numbers. So you should probably put the logic to generate each type of question into their own case
s.
For subtraction questions, you can check which number is larger first. Then arrange them appropriately to avoid the result being a negative number.
For division questions, you can generate two numbers, and produce a question with the product of the two numbers being divided by one of the numbers. This way you guarantee an integer solution. Something like this:
let number1 = Int.random(in: 0..<10)
let number2 = Int.random(in: 0..<10)
let product = number1 * number2
question = "\(product) / \(number1)"
Quiz app to pick questions from 8 group of questions randomly?
Thanks for the advices guys. But I found the way on how to do it. I only changed the pickQuestion function.
func pickQuestion ()
{
if Questions.count > 0 && questionscount < 8{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("KEK")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("KEK")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions[QNumber].Answers[i], for: UIControlState.normal)
}
print(QNumber)
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 13{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("M")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("M")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("M")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("M")}[QNumber].Answers[i], for: UIControlState.normal)
}
print(QNumber)
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 18{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("N")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("N")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("N")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("N")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 24{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("A")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("A")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("A")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("A")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 30{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("ΑΔ")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("ΑΔ")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("ΑΔ")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("ΑΔ")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 35{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("ΕΠ")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("ΕΠ")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("ΕΠ")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("ΕΠ")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 44{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("T")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("T")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("T")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("T")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else if Questions.count > 0 && questionscount < 50{
QNumber = Int(arc4random_uniform(UInt32(Questions.filter{$0.Question.hasPrefix("ΑΝΘ")}.count)))
questionscount += 1
questionLabel.text = Questions.filter{$0.Question.hasPrefix("ΑΝΘ")}[QNumber].Question
self.title = "Ερώτηση: \(Int(questionscount))/50"
answerNumber = Questions.filter{$0.Question.hasPrefix("ΑΝΘ")}[QNumber].Answer
for i in 0..<buttons.count{
buttons[i].setTitle(Questions.filter{$0.Question.hasPrefix("ΑΝΘ")}[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
}else
{
let alert = UIAlertController(title: "Σκόρ", message: "Απάντησες σωστά τις \(Int(score)) από τις \(Int(questionscount)) ερωτήσεις! \n \(String(format: "%.0f",(score/questionscount*100))) %", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Μενού", style: UIAlertActionStyle.default, handler: { action in
self.navigationController?.popToRootViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
Hide()
}
How to generate a random number in Swift?
Swift 4.2+
Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types.
You can call the random()
method on numeric types.
let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()
How to generate randon quiz questions when we have more than 100 or more questions in ios
let randomIndex = Int(arc4random_uniform(UInt32(questionsArray.count)))
print(questionsArray[randomIndex])
Use above code to pick random questions from an array
Related Topics
Must Call a Designated Initializer of The Superclass 'Day' Error
Uirefreshcontrol Glitching in Combination with Custom Tableviewcell
Connect Physicsbodies on Tilemap in Spritekit
Audiokit Seems to Receive Only The First Three Numbers of Sysex Midi Messages
Moving from Nsurlconnection to Nsurlsession for Soap Post in Swift
Swift Dictionary Initialization of Custom Type Gives: '>' Is Not a Postfix Unary Operator Error
Set Maximum Characters (To One) in a Nstextfield in Swift
How to Name File Stored to Files App via Uactivityviewcontroller
How to Set .Realm File on Realm
Preload a Scene to Prevent Lag
Validate Unicode Code Point in Swift
How to Get Buffer from Avaudioengine's Installtap at High Frequency
Nstimer Scheduledtimerwithtimeinterval and Target Is "Class Level Function"
How to Use The Spritekit Method Body(At: Cgpoint)
Disable Bringing App Window to Front. After Closing Another Window