Hash Tables: Ransom Note

  • + 1 comment

    My Swift answer

    import Foundation
    // boilerplate i/o
    public func getLine() -> String {
        var buf = String()
        var c = getchar()
         while c != EOF && c != 10 {
            buf.append(UnicodeScalar(UInt32(c)))
            c = getchar()
        }
        return buf
    }
    
    public func readLn() -> String {
        return getLine()
    }
    
    public func readLn() -> Int {
        return Int(getLine())!
    }
    
    public func readLn() -> [String] {
        return getLine().componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    }
    
    public func readLn() -> [Int] {
        let words: [String] = readLn()
        return words.map { Int($0)! }
    }
    
    //solution starts here
    func canMakeRansomNote(source: String, message: String) -> String {
      var wordHash = [String:Int]()
      
      for word in source.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()){
        if let wordCount = wordHash[word] {
          wordHash[word] = wordCount + 1
        } else {
          wordHash[word] = 1
        }
      }
      
      for word in message.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()){
        if let wordCount = wordHash[word] {
          if wordCount > 0 {
             wordHash[word] = wordCount - 1
          } else {
            return "No"
          }
        } else {
          return "No"
        }
      }
      return "Yes"
    }
    
    var firstLine: String = readLn()
    print(canMakeRansomNote(readLn(), message:readLn()))