DEV Community

Learning Algorithms with JS, Python and Java 7: Anagrams

tommy-3 on August 28, 2018

This is the seventh article of my attempts to follow Stephen Grider's Udemy course in three different languages. JavaScript solutions are by Stephe...
Collapse
 
kepta profile image
Kushan Joshi • Edited

Great article Tommy!

I love finding smaller solutions to problems, here is a similar attempt to your question on anagrams.

function anagrams(a, b) {
  a = a.replace(/[^\w]/g, "").toLowerCase();
  b = b.replace(/[^\w]/g, "").toLowerCase();

  if (a.length !== b.length) return false;

  return [...a].sort().join() ===  [...b].sort().join()
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
kepta profile image
Kushan Joshi • Edited

This is a great solution Sam, the only thing I worry about is that multiplication though theoretically is an O(1) operation, but in for strings of size > 50, we will have resort to Big integers and multiplication there is not exactly O(1).

Also played a bit of code golf with your algorithm

const primeSum = word =>
  word
    .map(char => primes.get(char.toLowerCase()))
    .filter(char => char !== undefined)
    .reduce((prev, cur) => prev * cur);
Collapse
 
stevenbrown163 profile image
Steven Brown

Nice thing about this method, you can use modulus to check if a string is a substring of another (“apple” to “applesauce”).

Thread Thread
 
kepta profile image
Kushan Joshi

That might give false positive for jumbled words, for example paple would pass the modulous check.