Skip to main content

Posts

Showing posts with the label string anagram

Prime Anagrams - Comparing Anagrams using Prime Numbers

Introduction In this post, we will use prime numbers to compare anagrams. We will assign the prime number to each character in a string and then multiply them. Two strings will be equal if their product is the same. Implementation in Java public class PrimeAnagram { static int [] alphaPrime = {5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107}; static String alphabets = "abcdefghijklmnopqrstuvwxyz"; public static void main(String[] args) { System.out.println(isPrimeAnagram("parse", "spare")); } private static boolean isPrimeAnagram(String value1,String value2) { return getPrime(value1) == getPrime(value2); } private static int getPrime(String value) { value = value.toLowerCase(); int productValue = 1; for(int index = 0; index < value.length(); index++) { productValue *= alphaPrime[ alphabets.indexOf(value.charAt(index)) ]; } return productValue; } } Conclusion We