elstiv
elstiv

Reputation: 377

Java matching a given word with combinations of same size

I have almost managed to accomplish this but not to the full. So what I need is for example I give the word DOG and the program will look into a text file and return DOG and GOD, i.e words that can be generated by the odds given only. My code is giving me all words that contain 'D', 'O' and 'G'. My code is this:

public class JavaReadTextFile {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        ReadFile rf = new ReadFile();

        String filename = "/Users/Elton/Desktop/OSWI.txt";
        String wordinput;
        String wordarray[] = new String[1];
        System.out.println("Input Characters: ");
        wordinput = input.nextLine();
        wordarray[0] = wordinput;

        System.out.println(wordinput.length());

        try {
            String[] lines = rf.readLines(filename);

            for (String line : lines) {
                if (line.matches(wordarray[0] + ".*")) {
                    System.out.println(line);
                }
            }
        } catch (IOException e) {
            System.out.println("Unable to create " + filename + ": " + e.getMessage());
        }
    }
}

----- then i have:

public class ReadFile {
    String [] cName = new String [100];

    public String[] readLines(String filename) throws IOException {  
        FileReader fileReader = new FileReader(filename);  

        BufferedReader bufferedReader = new BufferedReader(fileReader);  
        List<String> lines = new ArrayList<String>();  
        String line = null;  

        while ((line = bufferedReader.readLine()) != null ) {   
          cName[0] = line.split(" ")[0];  
          lines.add(cName[0]); 
        }  

        bufferedReader.close();  

        return lines.toArray(new String[lines.size()]);  
    }     
}

Upvotes: 2

Views: 1087

Answers (3)

nem035
nem035

Reputation: 35491

If I understand you correctly, you want to display all the anagrams of a word?

Change your method readLines() to return an ArrayList instead of an array.

ArrayList<String> readLines(String fname) {

    File file = new File(fname);
    ArrayList<String> list = null;

    try {
        Scanner scanner = new Scanner(file);
        list = new ArrayList<String>();

        while (scanner.hasNext()) {
            String currentWord = scanner.next();
            if (!currentWord.isEmpty()) {
                list.add(currentWord);
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return list;
}

The use this function with input parameter dictionary being the ArrayList you return from readLines. The function uses the fact that two anagrams like "DOG" and "GOD" are equal strings when both are sorted (i.e. "DGO" equals "DGO")

public ArrayList<String> getAnagrams(String word, ArrayList<String> dictionary) {
    if(word == null || dictionary == null) {
        return null;
    }

    ArrayList<String> anagrams = new ArrayList<String>();
    char[] sortedChars = word.toCharArray();
    Arrays.sort(sortedChars);
    for(String item : dictionary) {
        char[] sortedDictionaryItem = item.toCharArray();
        Arrays.sort(sortedDictionaryItem);
        if(Arrays.equals(sortedChars, sortedDictionaryItem)) {
            anagrams.add(item);
        }
    }
    return anagrams;
}

If you don't like the changes I am suggesting, you can also do the following. In the loop where you do:

if (line.matches(wordarray[0] + ".*")) {
    System.out.println(line);
}

You can check if the two strings are permutations of each other:

if (isPermutation(line, wordarray[0]) {
    System.out.println(line);
}

By adding these two functions:

String sortString(String s) {
    char[] chars = s.toCharArray();
    java.util.Arrays.sort(chars);
    return new String(chars);
}

boolean isPermutation(String s1, String s2) {
    if(s1.length() != s2.length()) {
        return false;
    }
    s1 = sortString(s1);
    s2 = sortString(s2);
    return (s1.compareTo(s2) == 0);
}

Upvotes: 0

mirmdasif
mirmdasif

Reputation: 6354

I can see you are able to read the words from file. Rest of the work is simple. algorithm will be something like this

  • sort inputWord

  • sort the word you read from file

  • if both word is same print or add it to some list.

And here is simple demonstration of above algorithm you can modify it to your need.

    public class App {

        static String sortString (String str) {
            char []chars = str.toCharArray();
            sort(chars);
            return new String(chars);
        }
        public static void main(String... args) {
            String inputWord = "DoG";
            String readWord = "God";
            inputWord = inputWord.toUpperCase();
            readWord = readWord.toUpperCase();
            inputWord = sortString(inputWord);
            readWord = sortString(readWord);

            if(inputWord.equalsIgnoreCase(readWord)) {
                System.out.println(readWord);// you can add it to your list
            }

        }
    }

Upvotes: 1

user9349193413
user9349193413

Reputation: 1233

This may help you adapt your code.

import java.util.regex.* ;

public class Find_Dogs_And_Gods
{
    public static void main(String []args)
    {
        String line = "2ldoghmDoggod" ;

        Pattern p = Pattern.compile("[d,D,g,G][o,O][d,D,g,G]") ;
        Matcher m = p.matcher(line) ;

        while(m.find() )
        {
            System.out.println( m.group() ) ;
        }
    }
}

Upvotes: 0

Related Questions