Created
December 30, 2017 02:25
-
-
Save earlonrails/c2bc351c68ab408cf01219f832b73fde to your computer and use it in GitHub Desktop.
ES6 javascript solution for https://www.hackerrank.com/challenges/ctci-ransom-note/problem
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
#!/usr/bin/env node | |
class RansomNote { | |
constructor(words, magazineWords) { | |
this.words = this.parseDocument(words) | |
this.magazine = this.parseDocument(magazineWords) | |
} | |
parseDocument(words) { | |
var wordHash = {} | |
words.forEach((w) => { | |
if (!wordHash[w]) { wordHash[w] = 0 } | |
wordHash[w]++ | |
}) | |
return wordHash | |
} | |
validMagazine() { | |
let {words, magazine} = this | |
if (Object.keys(words).length < 0 || Object.keys(magazine).length < 0) { | |
return 'No' | |
} | |
for (var key of Object.keys(words)) { | |
if (magazine[key] >= words[key]) { | |
continue | |
} else { | |
return 'No' | |
} | |
} | |
return 'Yes' | |
} | |
} | |
let magazineWords = "apgo clm w lxkvg mwz elo bg elo lxkvg elo apgo apgo w elo bg".split(' ') | |
let ransomWords = "elo lxkvg bg mwz clm w".split(' ') | |
let note = new RansomNote(ransomWords, magazineWords) | |
console.dir(note) | |
console.log("valid: ", note.validMagazine()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment