In this post I would be discussing a method to test whether two integers are anagrams of each other or not. Two integers are anagram of each other if one can be formed by rearranging each digit of the other, using all digits equally once. For example 122333 is an anagram of 132323.
The easiest or rather the first approach which usually comes in the minds of students is to store the digits of each integer into an array and compare the two arrays after sorting them in ascending or descending order. The approach would obviously give correct output but the logic is not good in terms of efficiency due to sorting requirement.
Another approach is to take a single dimension integer array of size ten. The idea is to use each element of the array for one of the ten digits. For each occurrence of a digit in the first number we would increment the corresponding array element once and for each occurrence of a digit in the second number we would decrement the corresponding array element once. This way all the element should be zero in case the two integers are anagrams of each other. The Java program to test for numeric anagrams using the above logic would be as follows:
class NumericAnagram{ public static boolean isAnagram( int a, int b ){ if( a == b ) return true; int freq[] = new int[ 10 ]; for( int temp = a; temp > 0 ; temp /= 10 ){ freq[ temp % 10 ]++; } for( int temp = b; temp > 0 ; temp /= 10 ){ freq[ temp % 10 ]--; } for( int n: freq ){ if( n != 0 ) return false; } return true; } public static void main( String args[] ){ System.out.println( isAnagram( 122333, 132323 ) ); System.out.println( isAnagram( 122333, 1323232 ) ); System.out.println( isAnagram( 1, 2 ) ); } }
The above program uses enhance for-statement on line number 11. Please refer to my earlier post “Enhanced for loop“, for the details of enhanced for-statement. As usual, the main function has purposely been kept to minimum and its expected that students will write appropriate input/output statements as per the requirement.