Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. //anagram
  2.  
  3. //iceman is an anagram of cinema
  4.  
  5. /*
  6. thinking out loud...
  7. reduce each word to an object.
  8. problem, JSON stringify doesn't understand order doesn't matter.
  9. double for loop
  10. sweep through a word, see if it occurs again.
  11.  
  12. splicing things...
  13. push and splice
  14. ////////////////////////////////
  15. condense both words to have no spaces, all lowercase.
  16. then check that word1 and word2 are equal lengths.
  17. then we can check to see if these are anagrams.
  18. split each word to be arrays.
  19. double for loop
  20. iterate through word1
  21. if you find that character in word2, splice it out of word2.
  22. if it truly was an anagram,
  23. word2 will just be an empty array.
  24. */
  25.  
  26.  
  27. function isAnagram(word1, word2) {
  28. var word1 = word1.toLowerCase().split(' ').join('').split('');
  29. var word2 = word2.toLowerCase().split(' ').join('').split('');
  30. if (word1.length !== word2.length) {
  31. return false;
  32. }
  33. for (var i = 0; i < word1.length; i++) {
  34. for (var j = 0; j < word2.length; j++) {
  35. if (word1[i] === word2[j]) {
  36. word2.splice(j, 1);
  37. }
  38. }
  39. }
  40. return word2.length === 0;
  41. }
  42.  
  43. //console.log('sTring Cheese'.toLowerCase().split(' ').join('').split(''));
  44. console.log(isAnagram('iceman', 'cinema'));
  45. console.log(isAnagram('Rocket Boys', 'October Sky'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement