import Foundation
// Function to generate a random math problem
func generateMathProblem() -> String {
let num1 = Int.random(in: 1...10)
let num2 = Int.random(in: 1...10)
let operatorOptions = ["+", "-", "*", "/"]
let selectedOperator = operatorOptions.randomElement()!
let mathProblem = "\(num1) \(selectedOperator) \(num2)"
return mathProblem
}
// Function to check if the user's answer is correct
func isAnswerCorrect(mathProblem: String, answer: Int) -> Bool {
if let expression = NSExpression(format: mathProblem),
let expectedResult = expression.expressionValue(with: nil, context: nil) as? Int {
return answer == expectedResult
}
return false
}
// Main function to handle the alarm
func alarmHandler() {
let mathProblem = generateMathProblem()
print("Solve the math problem: \(mathProblem)")
if let userAnswer = readLine(), let answer = Int(userAnswer) {
if isAnswerCorrect(mathProblem: mathProblem, answer: answer) {
print("Alarm Off. Problem solved!")
return
} else {
print("Incorrect answer. The alarm continues.")
alarmHandler()
}
}
}
// Set the alarm
print("Your alarm is set!")
alarmHandler()