Created
July 20, 2021 19:29
-
-
Save basil2style/9efdb7671ae0e4699095930498163d24 to your computer and use it in GitHub Desktop.
Hackerrank Ransom Note Problem
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
/** | |
*Direct Link: https://www.hackerrank.com/challenges/ctci-ransom-note/problem | |
*/ | |
function splitTextByReg(magazine, note) { | |
//Split both magazine words & note words by space -> Now we have two arrays | |
//From that arrays, check whether | |
let ransomNote = true; | |
// let magazineArr = magazine.split(" "); | |
// let noteArr = note.split(" "); | |
//create hashtable | |
let magazineMap = generateWordsMap(magazine); //{attack:1, dawn:1} | |
let noteMap = generateWordsMap(noteArr); | |
Object.keys(noteMap).forEach(function(word) { | |
if(magazineMap[word] !== noteMap[word]) { | |
ransomNote = false; | |
} | |
}); | |
return ransomNote===true? 'Yes':'No' ; | |
} | |
function generateWordsMap(wordArr) { | |
let wordOccurence = {}; | |
wordOccurence = wordArr.reduce((wordMap, word) => { | |
if(!Object.hasOwnProperty.call(wordMap, word)) { | |
wordOccurence[word] = 1; | |
} | |
else wordOccurence[word] = wordOccurence[word]+1; | |
return wordOccurence; | |
},{}); | |
return wordOccurence; | |
} | |
let magazine = "attack at dawn"; | |
let note = "Attack at dawn"; | |
console.log(splitTextByReg(magazine,note )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment