Skip to content

Instantly share code, notes, and snippets.

@rodrigolira
Last active June 18, 2018 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigolira/3c497eaba8bbfce17864e1f067faa95a to your computer and use it in GitHub Desktop.
Save rodrigolira/3c497eaba8bbfce17864e1f067faa95a to your computer and use it in GitHub Desktop.
Harmless Ransom Note algorithm implementation in javascript
// Implementation attempt of the Harmless Ransom Note algorithm.
// Create a function that receive two string parameters.
// The function should return "true" when the text int "noteText" can be created
// from words presented on "magazineText". It should return "false" otherwise.
function harmlessRansomNote(noteText, magazineText) {
var noteWords = noteText.split(" ");
var magazineWords = magazineText.split(" ");
var allWordsFound = true;
for (var i = 0; i < noteWords.length; i++) {
var wordIndex = magazineWords.indexOf(noteWords[i]);
if (wordIndex < 0) {
// Word could not be found
allWordsFound = false;
break;
} else {
magazineWords.splice(wordIndex, 1);
}
}
return allWordsFound;
}
var noteText1 = 'this is a secret note for you from a secret admirer';
var noteText2 = 'this is a note for you from a secret admirer';
var magazineText1 = 'puerto rico is a great place you must hike far from town to find a secret waterfall that i am an admirer of but note that it is not as hard as it seems this is my advice for you';
harmlessRansomNote(noteText1, magazineText1);
function harmlessRansomNote(noteText, magazineText) {
var noteWords = noteText.split(" ");
var magazineWords = magazineText.split(" ");
var magazineWordsHashtable = {};
magazineWords.forEach(word => {
if (!magazineWordsHashtable[word]) magazineWordsHashtable[word] = 0;
magazineWordsHashtable[word]++;
});
var allWordsFound = true;
noteWords.every(word => {
if (magazineWordsHashtable[word] && magazineWordsHashtable[word] > 0) {
magazineWordsHashtable[word]--;
return true;
} else {
allWordsFound = false;
return false;
}
});
return allWordsFound;
}
var noteText1 = 'this is a secret note for you from a secret admirer';
var noteText2 = 'this is a note for you from a secret admirer';
var magazineText1 = 'puerto rico is a great place you must hike far from town to find a secret waterfall that i am an admirer of but note that it is not as hard as it seems this is my advice for you';
harmlessRansomNote(noteText1, magazineText1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment