java - Getting All Possibilities - Schoolwork -


what need take string array each element having exact length of 2, , find possible combinations of the elements, using each character within each string. mean string array {"ss", "ff"} returns "sf", "sf", "sf", "sf". have tried loop method counts iteration , chooses letter based on that, works arrays single element:

    public string [] generatepossibilities(string [] s) {     if(s[0].length() != 2)         throw new illegalargumentexception();      string [] r = new string [s.length * 2];      for(int = 0; < r.length; i++)     {         r[i] = getpossibility(i, s);     }      return r; }  private string getpossibility(int iteration, string [] source) {     int [] choose = new int [source.length];     for(int = 0; < choose.length; i++)     {         choose[i] = 0;     }      for(int = choose.length - 1; >= 0; i--)     {         if(iteration < 1)             break;          choose[i] = 1;         iteration--;     }      string result = "";     for(int = 0; < source.length; i++)         result += source[i].substring(choose[i], choose[i] + 1);      return result; } 

solved sven!

    public string [] generatepossibilities(string [] s) {     if(s[0].length() != 2)         throw new illegalargumentexception();      arraylist<string> ra = new arraylist<string>();      for(int = s.length - 1; >= 0; i--)     {                    for(int j = 0; j < s[i].length(); j++)         {             string c = s[i].substring(j, j + 1);              if(ra.size() < 2)             {                 ra.add(c);             }              else             {                 for(int k = 0; k < ra.size(); k++)                 {                     string s1 = ra.get(k);                     if(s1.substring(0, 1).equalsignorecase(c))                         continue;                     else                     {                         s1 = c + s1;                         ra.add(s1);                     }                 }             }         }          for(int j = 0; j < ra.size(); j++)         {             if(ra.get(j).length() != s.length - i)             {                 ra.remove(j);                 j--;             }         }     }      string [] r = new string [ra.size()];     for(int = 0; < r.length; i++)     {         r[i] = ra.get(i);     }     return r; } 

i iterate array of character tuples last element first. in each step append each current character possibilities of last iteration. therefore double elements in each step. example in first iteration have {ff} , result 2 strings "f" , "f". in next step take each character of {ss} , append each string of last step getting "sf", "sf", "sf" , "sf". continue further character tuples.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -