Skip to content

Instantly share code, notes, and snippets.

@BrandonShega
Last active March 6, 2017 18:07
Show Gist options
  • Save BrandonShega/57c3350398e275a82d491ab4de11d479 to your computer and use it in GitHub Desktop.
Save BrandonShega/57c3350398e275a82d491ab4de11d479 to your computer and use it in GitHub Desktop.
Ease the StockBroker
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