An anagram is a type of word play, the result of rearranging the letters of a wo
ID: 3764826 • Letter: A
Question
An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example Torchwood can be rearranged into DoctorWho. Any word or phrase that exactly reproduces the letters in another order is an anagram. However, the goal of serious or skilled anagrammatists is to produce anagrams that in some way reflect or comment on the subject. Such an anagram may be a synonym or antonym of its subject, a parody, a criticism, or praise; e.g. William Shakespeare = I am a weakish speller
Another example is "silent" which can be rearranged to "listen". The two can be used in the phrase, "Think about it, SILENT and LISTEN are spelled with the same letters". (To mean "the quieter you become, the more you can hear").
Write a program to create a class named CheckAnagram that prompts the user to enter two strings and, if they are anagrams, displays two strings are anagrams, and displays two strings are not anagrams if they are not anagrams.
Below is the list of the required methods in your program:
/** Return true if the s1 and s2 are anagrams */
public static boolean isAnagram(char[] s1, char[] s2);
/** Return a sorted array of s */
/** (i.e) For the array, s = [c, d, a, f, g], */
/** this method should return [a, c, d, f, g] */
public static char[] sort(char[] s);
NOTE: You are NOT allowed to use Java provided array sorting method (i.e java.util.Arrays.sort()). You MUST implement your own sorting algorithm.
Explanation / Answer
import java.io.*;
import java.util.*;
class main{
public static boolean isAnagram(char[] s1, char[] s2){
s1=sort(s1);
s2=sort(s2);
if (Arrays.equals(s1, s2))
return true;
return false;
}
public static char[] sort(char[] s){
int l=s.length;
for(int i=0;i<l-1;i++){
int ind=i;
for(int j=i+1;j<l;j++){
if(s[ind]>s[j]){
ind=j;
}
}
char c=s[ind];
s[ind]=s[i];
s[i]=c;
}
return s;
};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
s1=s1.toLowerCase();
s2=s2.toLowerCase();
System.out.println(isAnagram(s1.toCharArray(),s2.toCharArray()));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.