Last active
March 6, 2017 18:07
-
-
Save BrandonShega/57c3350398e275a82d491ab4de11d479 to your computer and use it in GitHub Desktop.
Ease the StockBroker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func balanceStatements(_ list: String) -> String { | |
var totalBuy = 0 | |
var totalSell = 0 | |
var malformedCount = 0 | |
var malformedOrders = [String]() | |
let pattern = "\\w+ \\w+ \\d+\\.\\d+ \\w+" | |
let orders = list.components(separatedBy: ",").filter { !$0.isEmpty } | |
for order in orders { | |
if let _ = order.range(of: pattern, options: .regularExpression) { | |
let orderComponents = order.components(separatedBy: " ") | |
let shares = Double(orderComponents[1]) ?? 0 | |
let amount = Double(orderComponents[2]) ?? 0 | |
if order.hasSuffix("B") { | |
totalBuy += Int((shares * amount).rounded()) | |
} else { | |
totalSell += Int((shares * amount).rounded()) | |
} | |
} else { | |
malformedOrders.append(order) | |
malformedCount += 1 | |
} | |
} | |
let total = "Buy: \(totalBuy) Sell: \(totalSell)" | |
return malformedOrders.count == 0 ? total : "\(total); Badly formed \(malformedCount): \(malformedOrders.joined(separator: " ;")) ;" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment