Last active
May 25, 2019 13:08
-
-
Save marianolatorre/40aa85b55cfea2437a51dff2c4650ae7 to your computer and use it in GitHub Desktop.
30 days of code: day 8 dictionaries and maps in SWIFT2
This file contains 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
import Foundation | |
func telephones(input : String) { | |
var map = [String : String]() | |
let newlineChars = NSCharacterSet.newlineCharacterSet() | |
let spaceLineChars = NSCharacterSet.whitespaceCharacterSet() | |
let allLines = input.utf16.split { newlineChars.characterIsMember($0) }.flatMap(String.init) | |
guard allLines.count > 0 else{ | |
return | |
} | |
let nLines = Int(allLines[0])! | |
for aLine in allLines[1...nLines] { | |
let data = aLine.utf16.split { spaceLineChars.characterIsMember($0) }.flatMap(String.init) | |
map[data[0]] = data[1] | |
} | |
for aLine in allLines[nLines+1...allLines.count-1] { | |
let number : String? = map[aLine] | |
if let number = number { | |
print ("\(aLine) \(number)") | |
}else{ | |
print("Not found") | |
} | |
} | |
} | |
let input = "3\nsam 99912222\ntom 11122222\nharry 12299933\nsam\nedward\nharry\n" | |
telephones(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution to this problem using Swift 2
https://www.hackerrank.com/challenges/30-dictionaries-and-maps
Sample Input
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
Sample Output
sam=99912222
Not found
harry=12299933