Created
May 1, 2016 19:40
-
-
Save kiichi/ac1d253bb204a84dcaa77aaa190a54c5 to your computer and use it in GitHub Desktop.
NSScanner Example: Fast Data parsing using swift
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
| // Use by piping | |
| // cat input22.txt | ./MyScanner | |
| // This is very slow | |
| // let xy = (readLine()!).characters.split(" ").map{Int(String($0))!} | |
| import Foundation | |
| var str = "" | |
| while true { | |
| guard let input = readLine() else { | |
| break | |
| } | |
| str += input | |
| } | |
| // Test | |
| //let str = "1000000 2000 400 2938 292919" | |
| let scanner:NSScanner = NSScanner.localizedScannerWithString(str as String) as! NSScanner | |
| let skipChars = NSMutableCharacterSet(charactersInString: " ") // not sure if it contributes for speed | |
| scanner.charactersToBeSkipped = skipChars | |
| var count = 0 | |
| while true { | |
| var num:Int = 0 | |
| let success = scanner.scanInteger(&num) | |
| if success { | |
| //print("Read \(num)") | |
| count = count + 1 | |
| } | |
| else { | |
| break | |
| } | |
| } | |
| print("Completed: \(count) numbers found") | |
| ///////////////////////////////////////////////////////////// | |
| // Benchmark Bash Script | |
| //SECONDS=0 | |
| //cat input06.txt | ./HackerRanking | |
| //duration=$SECONDS | |
| //echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed." | |
| ///////////////////////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment