An anagram is a word obtained by reordering the letters of another word. For exa
ID: 3585382 • Letter: A
Question
An anagram is a word obtained by reordering the letters of another word. For example, “once” and “cone” are anagrams. Note that each letter must be reused exactly once, so anagrams must have the same number of letters.
Which word in the English language has the most anagrams? Let us take “words in the English language” to mean words in the le “words.txt”, which is posted on Moodle.
Write a program called MostAnagrams to nd the word with the most anagrams. Your program should take no input and produce a single integer, the maximum number of anagrams, as output.
For this problem you may nd the String method toCharArray(), the String constructor that takes a character array argument, and the method java.util.Arrays.sort() useful
This is the starter code given by professor:
import java.io.File; import java.io.FileNotFoundException; import java.util·Scanner; import java.util.ArrayList; public class MostAnagrams public static void main(String 1 args) File file -new File("../resource/asnlib/publicdata/words.txt"); int max 0; try Scanner scannernew Scanner(file); while (scanner.hasNext)) f String line - scanner.next (); // read in the next word // Now do something with the word scanner.close); catch (FileNotFoundException e) { e.printStackTrace(); compute max, the maximum number of analgrams for any word System.out.println( max);Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class MostAnagrams {
public static void permute(String a, int low, int high, ArrayList<String> data)
{
char temp;
char[] p = a.toCharArray();
if (low == high){
data.add(a);
}
else
{
for (int i = low; i <= high; i++)
{
temp = p[i];
p[i] = p[low];
p[low] = temp;
permute(String.valueOf(p), low+1, high,data);
temp = p[i];
p[i] = p[low];
p[low] = temp;
}
}
}
public static void main(String[] args) {
File file = new File("words.txt");
int max = 0;
int count;
ArrayList<String> data = new ArrayList<String>();
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String line = scanner.next();
String[] arr = line.split("\s+");
data.clear();
for(int i = 0; i<arr.length; i++){
data.clear();
permute(arr[i],0,arr[i].length()-1, data);
System.out.println(arr[i] + " " + data.size());
if (max < data.size()){
max = data.size();
}
}
}
System.out.println(max);
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.