-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathransom-note.js
88 lines (73 loc) · 1.99 KB
/
ransom-note.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
*
* ------------------
* | TEMPLATE |
* ------------------
*
*
*
* Harold is a kidnapper who wrote a ransom note,
* but now he is worried it will be traced back to
* him through his handwriting. He found a magazine
* and wants to know if he can cut out whole words
* from it and use them to create an untraceable
* replica of his ransom note. The words in his
* note are case-sensitive and he must use only
* whole words available in the magazine. He cannot
* use substrings or concatenation to create the words
* he needs.
*
* Given the words in the magazine and the words in
* the ransom note, print Yes if he can replicate
* his ransom note exactly using whole words from
* the magazine; otherwise, print No.
*
* For example, the note is "Attack at dawn". The
* magazine contains only "attack at dawn". The
* magazine has all the right words, but there's
* a case mismatch. The answer is .
*
*
*
* function chechMagazine(m,n) { // m[] -> magazine, n[] -> note
* // prints yes of all words in note are in m to print full message
* }
* e.g.
* magazine = [ive, got, a, lovely, bunch, of, coconuts]
* note = [ive, got, some, coconuts]
* checkMagazine(magazine, note); // prints `No`
*
*
* */
/*
*
* ***** SOLUTION
*
* */
function checkMagazine(magazine, note) {
// initialize magMap
const magMap = {};
// use for loop to populate magMap
for(let i = 0; i < magazine.length; i++) {
magMap[magazine[i]] = magMap[magazine[i]] + 1 || 1;
}
// loop through to note and check with map to see if all the words are there
for(let word of note){
if(!magMap[word]){
console.log("No");
return
};
magMap[word] --
};
console.log("Yes");
};
/*
*
* ***** TESTS
*
* */
const mag1 = ["give", "me", "one", "grand", "today", "night"];
const note1 = ["give", "one", "grand", "today", "today"];
const mag2 = ["two", "times", "three", "is", "not", "four"]
const note2 = ["two", "times", "two", "is", "four"]
console.log(checkMagazine(mag1, note1));