Hangout With Anagram in java

You are given with a words of array, now you need list only anagrams as output array. Anagram is a direct word ,by rearranging letters of a words or phrase produces new word or phrase.



import java.util.*;
public class HangoutWithAnagram {
public static String[] hangoutWithAnagrams(String input1)
{
String [] output=input1.split(" ");
int count=0;
List<String> value=new ArrayList<String>();
String [] sorted=new String[output.length];
//sorting words in the array in ascending order and saving in array.
for(int i=0;i<output.length;i++){
String x=output[i]; //saving in string
char [] a=x.toCharArray(); //dividing string into arrays
Arrays.sort(a); //sorting array in alphabetical order
x=new String(a); //saving array in string.
sorted[i]=x; //saving sorted string in sorted array.
}
//finding unique words in array
for(int j=0;j<sorted.length;j++){
String b=sorted[j];
for(int k=0;k<sorted.length;k++){
String c=sorted[k];
if(b.equals(c)){
count++;
}
}
if(count>1){
value.add(output[j]); //identifies the unique word in the array.
}
count=0;
}
String [] out=value.toArray(new String [value.size()]);
return out;
}
public static void main(String [] args){
Scanner in = new Scanner(System.in);
String[] output = null;
String ip1 = in.nextLine().trim();
output = hangoutWithAnagrams(ip1);
for(int output_i=0; output_i < output.length; output_i++) {
System.out.println(String.valueOf(output[output_i]));
}
in.close();
}
}
Input:
tea ate eat apple java vaja cut utc

Output:
tea
ate
eat
java
vaja
cut
utc

Comments

Popular posts from this blog

Reasoning-Number Series

Profit and Loss

Reasoning-Letter Series