Unscramble Letters in Java - Get all possible combinations of the letters

cpu-word, java, scramble

Solution

Starting with alphabetized key, 'aehrt', you can find all possible combinations of letters using the following method:

- start with: `S0 = {}`

- next, take `a`: `S1 = a⋅S0 ∪ S0 ∪ {a} = {a}`

- next, take `e`: `S2 = e⋅S1 ∪ S1 ∪ {e} = {ae, a, e}`

- next, take `h`: `S3 = h⋅S2 ∪ S2 ∪ {h} = {aeh, ah, eh, ae, a, e, h}`

- etc...

once you have `S5` (the entire set of combinations) check them all against your map.

public static void main(String... args){     
    Set<String> set = new TreeSet<String>();
    String key = "aehrt";

    //S1 = c*S0 ∪ {c} ∪ S0
    for(int z = 0; z < key.length();z++) {
        Set<String> temp = new HashSet<String>();
        char c = key.charAt(z);        

        for(String str: set)
            temp.add(str + c); // ∪ c*S0
        set.add(c+"");         // ∪ {c}
        set.addAll(temp);      // ∪ S0
    }

    System.out.println(set);
}

output: [a, ae, aeh, aehr, aehrt, aeht, aer, aert, aet, ah, ahr, ahrt, aht, ar, art,
         at, e, eh, ehr, ehrt, eht, er, ert, et, h, hr, hrt, ht, r, rt, t]

Problem

Solved: What I was asking was Solved but feel free to answer with alternate methods. here's the letter unscrambler made with the answer. Project Page I am currently an AP Computer Science student. I have been working on a letter unscrambler that reads in a dictionary and prints a list of words possible with the letter set inputted. To this end I make a map with `Map<String,Set<String>>` in which "earth" would be entered under the key "aerht" and in the corresponding set. ``` Example How Would I generate all of these: CAKE -> ACEK A C E K AC CE EK ACE CEK ACEK AE CK AEK ACK AK ``` The problem I am running into is that that some key values aren't being checked as currently I take in a set of numbers and alphabetize the characters eg earth->aehrt yet this skips combos such as aht->hat or eht -> the. So basically my Question would be how to simplify the process of obtaining all alphabetical combos contained in such a key. eg earth-> aehrt,a,ae,aeh,aehr,ah,ahr,ahrt,aer,aert and so on so that I can crossreference all these keys with those in the dictionary I read in. letters[] contains a,e,h,r,t in order. Also, test is an ArrayList of Set. Key is "aehrt". ``` for(int z = 0; z<key.length();z++) { Set<String> temp = new HashSet<String>(); //s1 = t*s0 ∪ {t} ∪ s0 = {t} for(String str: test.get(z)) //t*s0 str+=letters[z]; test.get(z).add(letters[z]); //{t} test.get(z).addAll(test.get(z-1));//s0 test.get(z).addAll(temp); } ```

Original source