Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@clarketm
Last active August 12, 2016 04:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clarketm/c2593a1c131fb8223d0d9e1c59197ad7 to your computer and use it in GitHub Desktop.
Save clarketm/c2593a1c131fb8223d0d9e1c59197ad7 to your computer and use it in GitHub Desktop.
Ransom Note Problem (JavaScript)
function isRansomNotePossible(newsArticle, ransomNote) {
var availableChars = {};
for (var r = 0; r < newsArticle.length; r++) {
var asciiCode = newsArticle.charCodeAt(r);
availableChars[asciiCode] = (availableChars[asciiCode] || 0) + 1
}
for (var r = 0; r < ransomNote.length; r++) {
var asciiCode = ransomNote.charCodeAt(r);
availableChars[asciiCode] = (availableChars[asciiCode] || 0) - 1;
if (availableChars[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