Question

I've created a program that takes a string, such as "computer", and outputs all dictionary words that can be formed from it. However I'm having trouble trying to figure out what the program's Big-O efficiency is, as it uses recursion and binarySearch.

Also, can the program be made more efficient? I haven't studied hashmaps or other data structures yet.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class WordScramble {

    static String[] dictArr;
    static int index;

    // print permutation / combination of the characters of the string s (in order)
    public static void permWord(String s) { permWord("", s); }

    private static void permWord(String prefix, String s) {
        int n = s.length();
        if (n != 0){
            for (int i = 0; i < n; i++)
               permWord(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
        }
        index = Arrays.binarySearch(dictArr, prefix);
        if (index > 0)
            System.out.println(prefix);
    }
    public static ArrayList<String> getLines(File f) throws FileNotFoundException { 
        ArrayList<String> dict = new ArrayList<String>();
        Scanner scan = new Scanner(f);
        while (scan.hasNext()){
            dict.add(scan.next());
        }
        scan.close();
        return dict;
    }
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("wordlist.txt");
        ArrayList<String> dictionary = getLines(f);
        dictArr = new String[dictionary.size()];
        dictArr = dictionary.toArray(dictArr);
        permWord("computer");       
    }
}
Was it helpful?

Solution

A better way would be to scan the dictionary and check which words are anagrams of the original word.

You can do this check by matching the count of each letter in the original word.

Complexity O(k) where k is the total number of letters in all the words in the dictionary.

This link shows more ways to approach such a problem. Best algorithm to find anagram of word from dictonary

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top