My solution in Swift :
/// Daily Challenge #4 - Checkbook Balancing let checkbook = """ 1233.00 125 Hardware;! 24.8?; 123 Flowers 93.5 127 Meat 120.90 120 Picture 34.00 124 Gasoline 11.00 123 Photos;! 71.4?; 122 Picture 93.5 132 Tires;! 19.00,?; 129 Stamps 13.6 129 Fruits{} 17.6 129 Market;! 128.00?; 121 Gasoline;! 13.6?; """ func analyseCheckbook(checkbook: String) { typealias CheckbookEntry = (number: String, description: String, expense: Double) let roundFormat = "%.2f" var count: Double = 0 var totalExpense: Double = 0 var checkbookEntries = [CheckbookEntry]() var cleanCheckbook = checkbook.filter { char -> Bool in char.isLetter || char.isNumber || char.isWhitespace || char == "." }.components(separatedBy: .newlines) let originalBalance = Double(cleanCheckbook.removeFirst()) ?? 0 cleanCheckbook.forEach { checkbook in let line = checkbook.components(separatedBy: .whitespaces) if line.count == 3 { checkbookEntries.append(CheckbookEntry(number: line[0], description: line[1], expense: Double(line[2]) ?? 0)) } } print("Original_Balance: \(originalBalance)") checkbookEntries.forEach { entry in count += entry.expense totalExpense += entry.expense print("\(entry.number) \(entry.description) Balance \(String(format: roundFormat, originalBalance - count))") } let averageExpense = (totalExpense / Double(checkbookEntries.count)) print("Total expense \(String(format: roundFormat, totalExpense))") print("Average expense \(String(format: roundFormat, averageExpense))") }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My solution in Swift :