-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hash Tables - Ransom Note.swift
39 lines (34 loc) · 1.04 KB
/
Hash Tables - Ransom Note.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Foundation;
let _ = readLine()!
let magazine = readLine()!
let note = readLine()!
func wordsFrequency(text: String) -> [String: Int] {
var dict = [String: Int]()
for word in text.components(separatedBy: " ") {
if dict.keys.contains(word) {
dict[word]! += 1
} else {
dict[word] = 1
}
}
return dict
}
func canReplicate(note: String, from magazine: String) -> Bool {
let magazineWordsFrequency = wordsFrequency(text: magazine)
let noteWordsFrequency = wordsFrequency(text: note)
return hasEnoughWords(in: magazineWordsFrequency, for: noteWordsFrequency)
}
func hasEnoughWords(in magazineFrequecy: [String: Int], for noteFrequency: [String: Int]) -> Bool {
for word in noteFrequency.keys {
guard let magazineWordCount = magazineFrequecy[word] else { return false }
if magazineWordCount < noteFrequency[word]! {
return false
}
}
return true
}
if canReplicate(note: note, from: magazine) {
print("Yes")
} else {
print("No")
}