java - Variable Number of Nested For Loops -
i'm making word unscrambler in java. right have program can print rearrangements of 3 letters chosen word 3 or more letters (no repeats). example, if parameter abcd, print this:
[[abc, abd, acb, acd, adb, adc, bac, bad, bca, bcd, bda, bdc, cab, cad, cba, cbd, cda, cdb, dab, dac, dba, dbc, dca, dcb]]
i'm filling 2d array list permutations. right 2d array has 1 array inside of it, contains permutations 3 letters. want 2d array have arrays permuations of 1 letter, 2 letters, 3 letters, , on, stopping @ length of word. problem need variable number of nested loops accomplish this. 3 letter permutations, have 3 nested loops. each 1 cycles through letters in parameter.
public static void printallpermuations(string word) { int len = word.length(); arraylist<string> lets = new arraylist<string>(); //this array of letters allows easier access //so don't have keep substringing (int = 0; < len; i++) { lets.add(word.substring(i, + 1)); } arraylist<arraylist<string>> newwords = new arraylist<arraylist<string>>(); newwords.add(new arraylist<string>()); (int = 0; < len; i++) { (int j = 0; j < len; j++) { (int k = 0; k < len; k++) { if (i != j && != k && j != k) //prevents repeats making sure indices different { newwords.get(0).add(lets.get(i) + lets.get(j) + lets.get(k)); } } } } system.out.println(newwords); }
i've looked @ other posts , i've heard recursion can solve this. don't know how implement that, though. , i've seen complicated solutions don't understand. i'm asking simplest solution possible, whether involves recursion or not.
with recursive method put 1 of looping in function pass loop parameters function. within function's loop, calls nest loop.
void loopfunction(arraylist<arraylist<string>> newwords, int level) { if (level == 0) { // terminating condition if (/* compare indices example passing down list them in */) { newwords.get(...).add(...); } } else {// inductive condition (int = 0; < len; i++) { loopfunction(newwords, level-1); } } }
so example need 3 levels of recursion start recursion with:
loopfunction(newwords, 3);
edit
since have been having trouble here working version. keeps list of indices compare against , builds string goes. rearranged words added 2d array @ each level lengths of words. recursion easiest think functionally , not change , keep variables immutable (unchangeable). code although update indices
rather create new copy convenience.
void loopfunction(arraylist<string> lets, arraylist<arraylist<string>> newwords, int level, arraylist<integer> indices, string word) { if (level == 0) { // terminating condition return; } else { // inductive condition (int = 0; < lets.size(); i++) { if (!indices.contains(i)) { // make sure no index equal int nextlevel = level-1; string nextword = word+lets.get(i); newwords.get(level-1).add(nextword); indices.add(i); loopfunction(lets, newwords, nextlevel, indices, nextword); indices.remove((integer) i); } } } }
Comments
Post a Comment