Identifying Anagrams
April 28, 2015
Our first solution sorts the words and compares their “signatures:”
(define (anagram1 str1 str2) (and (not (string=? str1 str2)) (equal? (sort charlist str1)) (sort charlist str2))))) > (anagram1 "DEPOSIT" "DOPIEST") #t > (anagram1 "STAR" "MOON") #f > (anagram1 "ZEBRA" "ZEBRA") #f
Wherever there is a sorting solution to a problem, there is also generally a searching solution also. Here, we increment an array of character counts when reading the first string, decrement it when reading the second string, and check that all the counts are zero:
(define (anagram2 str1 str2) (let ((counts (make-vector 256 0))) (define (add idx n) (vector-set! counts idx (+ (vector-ref counts idx) n))) (do ((cs (string->list str1) (cdr cs))) ((null? cs)) (add (char->integer (car cs)) 1)) (do ((cs (string->list str2) (cdr cs))) ((null? cs)) (add (char->integer (car cs)) -1)) (let loop ((i 65)) (cond ((= i 91) (not (string=? str1 str2))) ((not (zero? (vector-ref counts i))) #f) (else (loop (+ i 1))))))) > (anagram2 "DEPOSIT" "DOPIEST") #t > (anagram2 "STAR" "MOON") #f > (anagram2 "ZEBRA" "ZEBRA") #f
Our third solution maps each letter to a prime number, takes the product of the primes in each word, and compares them; beware of overflow in languages that don’t provide big integers natively:
(define (anagram3 str1 str2) (let ((letters (vector 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101))) (define (lookup c) (vector-ref letters (- (char->integer c) 65))) (and (not (string=? str1 str2)) (= (apply * (map lookup (string->list str1))) (apply * (map lookup (string->list str2))))))) > (anagram3 "DEPOSIT" "DOPIEST") #t > (anagram3 "STAR" "MOON") #f > (anagram3 "ZEBRA" "ZEBRA") #f
The first solution has time complexity O(n log n) for the sort; the other two are both O(n). But given its simplicity, I would probably prefer the first solution over the other two, changing to the second solution only if the first solution proved to be a bottleneck on my program. You can run the program at http://ideone.com/p1SAvl.
Haven’t done the prime number version but the first two were the solutions I went for – both in perl tho’
In Python.
Same solutions as Paul in Python. Added additional method using mapping onto primes and taking the product.
First version creates a bag out of each string and compares the bags for equality. The second solution removes all characters in the first string from the second string and checks that it results in the empty string, and vice versa.
Just one solution for the moment: a variant on the sorting method using two heaps. We save on work in the case that the two strings aren’t anagrams:
Here’s another one: generate all possible anagrams of a, and see if any are equal to b:
Not the most efficient way of solving the problem, but has a pleasant simplicity about it (and isanag only destructively modifies one of its arguments now).
Last one, pack the counts into a single 64 bit number. There are only 2 bits per character so eg. “AAAAC” is considered an anagram of “BBBBB”, but we always correctly detect a true anagram:
Your second solution doesn’t work too well on a Unicode system: you’d need an array of size 1,114,112. However, a hash table or similar map from characters to integers is the same in spirit.
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
void normalize(std::string& s)
{
s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), ::isspace));
s.erase(std::find_if_not(s.rbegin(), s.rend(), ::isspace).base(), s.end());
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
}
bool common(std::string& a, std::string& b)
{
normalize(a);
normalize(b);
if (a.size() != b.size()) return false;
if (a == b) return false;
return true;
}
std::map<char, int> analyze(std::string word)
{
std::map<char, int> data;
for (auto c: word) {
auto iter = data.find(c);
if (data.end() == iter) data[c] = 1;
else ++(iter->second);
}
return data;
}
bool are_anagrams1(std::string a, std::string b)
{
if (!common(a, b)) return false;
return analyze(a) == analyze(b);
}
bool are_anagrams2(std::string a, std::string b)
{
if (!common(a, b)) return false;
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
return a == b;
}
void test(const std::string& a, const std::string& b, std::ostream& out)
{
out << a << " and " << b << ": " <<
are_anagrams1(a, b) << ", " <<
are_anagrams2(a, b) << ‘\n’;
}
int main(int argc, char** argv)
{
std::cout.setf(std::ios_base::boolalpha);
test("deposit ", " dopiest", std::cout);
test("STOP", "pots", std::cout);
test("rite", "write", std::cout);
test("right", "write", std::cout);
test("same", "same", std::cout);
}
Sorry for the bad formatting in my previous post. Is there a way to delete it?
My discussion and solution in Java here http://www.capacode.com/?p=7