Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ransom Note Problem (ES6)
function isRansomNotePossible(newsArticle, ransomNote) {
let availableChars = new Map();
for (let r of newsArticle) {
let asciiCode = newsArticle.charCodeAt(r);
availableChars.set(asciiCode, (availableChars.get(asciiCode) || 0) + 1);
}
for (let r of ransomNote) {
let asciiCode = ransomNote.charCodeAt(r);
availableChars.set(asciiCode, (availableChars.get(asciiCode) || 0) - 1);
if (availableChars.get(asciiCode) < 0) {
console.log(`failed at character ${String.fromCharCode(asciiCode)}`);
return false;
}
}
return true;
}
// Examples
var newsArticle1 = "Federal prosecutors are investigating campaign contributions to Virginia Gov. Terry McAuliffe (D), and what they consider to be suspicious personal finances, as part of a public integrity probe that has lasted for more than a year, according to two officials familiar with the inquiry. Justice Department officials would not confirm or deny the investigation. Many details, including what prompted it, remain unclear, and one official said there is skepticism among prosecutors about whether it will lead to charges.";
var newsArticle2 = "Federal prosecutors are investigating campaign contributions to Virginia Gov. Terry McAuliffe (D).";
var newsArticle3 = "Skepticism was high.";
var ransomNote = "Federal";
console.log(isRansomNotePossible(newsArticle1, ransomNote)); // true
console.log(isRansomNotePossible(newsArticle2, ransomNote)); // true
console.log(isRansomNotePossible(newsArticle3, ransomNote)); // false //=> no "F"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment