Skip to content

Instantly share code, notes, and snippets.

@ararog
Last active July 28, 2016 19:47
Show Gist options
  • Save ararog/3959096 to your computer and use it in GitHub Desktop.
Save ararog/3959096 to your computer and use it in GitHub Desktop.
This program takes a text file with a list of words and checks how many words can be formed with the letters provided by command line argument.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
public class AnagramFinder {
/**
* @param args
*/
public static void main(String[] args) {
if(args.length == 2) {
AnagramFinder.findAnagrams(args[0], new File(args[1]));
}
else {
System.out.println("Invalid number of arguments!");
}
}
public static boolean isAnagram(String word, char[] validLetters) {
ArrayList<String> currentChars = new ArrayList<String>();
char[] wordChars = word.toCharArray();
for(char _char : wordChars)
currentChars.add(String.valueOf(_char));
int validLetterCount = 0;
for(char _char : validLetters) {
String value = String.valueOf(_char);
if(currentChars.contains(value))
validLetterCount++;
currentChars.remove(value);
}
return validLetterCount == word.length();
}
public static void findAnagrams(String word, File wordsFile) {
try {
System.out.println("Reading file");
BufferedReader reader = new BufferedReader(new FileReader(wordsFile));
char[] validLetters = word.toCharArray();
System.out.println("Searching anagrams");
ArrayList<String> lines = new ArrayList<String>();
String line;
while((line = reader.readLine()) != null)
if(line.length() == word.length())
if(isAnagram(line, validLetters))
System.out.println("Anagram found: " + line);
}
catch (FileNotFoundException e) {
System.out.println("Could not find file!");
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Could not process file!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment