Skip to content

Instantly share code, notes, and snippets.

@DavidGoussev
Forked from clarketm/ransomNoteProblem.js
Created August 12, 2016 04:26
Show Gist options
  • Select an option

  • Save DavidGoussev/236d9eb7a063a830514d8b4a58f00443 to your computer and use it in GitHub Desktop.

Select an option

Save DavidGoussev/236d9eb7a063a830514d8b4a58f00443 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