Full blown Java implementation of the Prime Product method mentioned in the tweet (Gist for full viewing):
packagetesting;importjava.math.BigInteger;importjava.util.List;importjava.util.stream.Collectors;importjava.util.stream.Stream;publicclassIsAnagramDemo{/* Get the primes we need */privatestaticfinalList<BigInteger>alphaPrimes=primes().limit(26).collect(Collectors.toList());/* Int encoding of lowercase a in unicode */privatestaticfinalintA_INT_ENCODING=97;/* Int encoding of lowercase z in unicode */privatestaticfinalintZ_INT_ENCODING=122;/*
Main method to demonstrate success
*/publicstaticvoidmain(String[]args)throwsException{assertisAnagram("stressed","desserts");assert!isAnagram("happy","sad");}/**
* Determines if two strings are anagrams using the prime product method
*
* @param s1 First input string
* @param s2 Second input string
* @return Boolean indicating anagram-ness
* @throws IllegalArgumentException Thrown when at least one of the input strings is invalid
*/publicstaticbooleanisAnagram(Strings1,Strings2)throwsIllegalArgumentException{returnprimeProduct(s1).equals(primeProduct(s2));}/**
* Converts a string to the corresponding product of prime values
*
* @param s Input string
* @return Big integer product of primes
* @throws IllegalArgumentException Thrown when strong contains chars outside of A-z
*/privatestaticBigIntegerprimeProduct(Strings)throwsIllegalArgumentException{/* Convert to lowercase char array */char[]chars=s.toLowerCase().toCharArray();BigIntegerproduct=BigInteger.ONE;for(charc:chars){/* Cast char to int */intcInt=(int)c;/* If the char is out of bounds we must throw an exception */if(cInt<A_INT_ENCODING||cInt>Z_INT_ENCODING){thrownewIllegalArgumentException("Character \""+c+"\" not valid");}/* Otherwise we can do the prime lookup */else{/* Prime value corresponding to this char */BigIntegerprimeVal=alphaPrimes.get(cInt%A_INT_ENCODING);/* Add this prime to our product */product=product.multiply(primeVal);}}/* Return the product */returnproduct;}/**
* @return Infinite stream of primes
*/privatestaticStream<BigInteger>primes(){returnStream.iterate(BigInteger.valueOf(2L),n->n.add(BigInteger.ONE)).filter(n->n.isProbablePrime(10));}}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Full blown Java implementation of the Prime Product method mentioned in the tweet (Gist for full viewing):