diff --git a/calc/main.swift b/calc/main.swift index f3612d3..3646c90 100644 --- a/calc/main.swift +++ b/calc/main.swift @@ -11,4 +11,75 @@ import Foundation var args = ProcessInfo.processInfo.arguments args.removeFirst() // remove the name of the program -print(Int(args[0])!) +// command-line calculator + +// validation +func validateArgs() { + for pos in 0...args.count-1 { + let operators = Set(["+", "-", "x", "/", "%"]) + if (pos % 2 == 1 && !operators.contains(args[pos])) { + print("Invalid operator entered for argument \(pos+1).\nExiting with code 1...") + exit(1) + } + else if (pos % 2 == 0 && Int(args[pos]) == nil) { + print("Invalid integer entered for argument \(pos+1).\nExiting with code 1...") + exit(1) + } + } +} + +// recursive x, / and % operands +func recurseOperands(calc_data: [String], pos: Int) -> [String] { + var calc_data_mutable = calc_data + var increment = 2 + + if pos > args.count - 1 { + return calc_data + } + else { + if (args[pos] == "x") { + let product = String(Int(calc_data.last!)! * Int(args[pos+1])!) + calc_data_mutable[calc_data_mutable.count-1] = product + } + else if (args[pos] == "/") { + if (Int(args[pos+1])! == 0) { + print("Error: Dividing by zero yields an undefined result.\nExiting with code 1...") + exit(1) + } + let dividend = String(Int(calc_data.last!)! / Int(args[pos+1])!) + calc_data_mutable[calc_data_mutable.count-1] = dividend + } + else if (args[pos] == "%") { + let remainder = String(Int(calc_data.last!)! % Int(args[pos+1])!) + calc_data_mutable[calc_data_mutable.count-1] = remainder + } + else { + calc_data_mutable.append(args[pos]) + increment = 1 + } + } + + return recurseOperands(calc_data: calc_data_mutable, pos: pos + increment) +} + +validateArgs() + +var calc_data: [String] = recurseOperands(calc_data: [args[0]], pos: 1) +var result: Int = Int(calc_data.first!)! + +for pos in 0...calc_data.count-1 { + if (pos < args.count) { + if (calc_data[pos] == "+") { + result += (Int(calc_data[pos+1])!) + } + else if (calc_data[pos] == "-") { + result -= (Int(calc_data[pos+1])!) + } + } + else { + print("Error: Calculation index is out of bounds.\nExiting with code 1...") + exit(1) + } +} + +print(result)