Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active May 24, 2016 01:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clarketm/ec6effab58ac4b5575d710c5e2f7db0c to your computer and use it in GitHub Desktop.
Save clarketm/ec6effab58ac4b5575d710c5e2f7db0c to your computer and use it in GitHub Desktop.
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