Finding all possible combinations - Simplifying many for loops into one

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Robbie551
    New Member
    • Apr 2012
    • 1

    Finding all possible combinations - Simplifying many for loops into one

    Hello Everyone, this is my first post on these forums, mostly because I never thought I would get this stumped ever and never had to really post on a Java forum before. So, to try and push myself harder in the Java world, I wanted to make a program that found all possible combinations of characters. I thought it would be kind of cool. I got it mostly, but it turned out to be a lot harder than I suspected ever. I commented it out to help anyone that might be reading this. Basically, what it does so far, is for each for loop added, it goes up a character in what it generates. Not how I intended it to work at all. What I want it to do is change the length based on a variable called Length. I've been working more then 2 hours trying to solve this issue, to no avail
    Here's my current code that I'm using:
    What it does is it actively writes the results to a file on my Desktop called test.txt.
    I current have 3 for loops set on it, which by the dumb principles on my programming, means a 3 char limit.
    Code:
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    
    public class Generate {
    	public static void Gen() throws IOException
    	{
    		//opens a file writing stream
    		FileOutputStream fos = new FileOutputStream("C:\\Users\\Ryan\\Desktop\\test.txt"); 
    		OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
    		//the character list I'm using
    		String CharList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    		//gets a list of characters
    		String[] CharSplit = CharList.split("");
    		String Str = "";
    		//generates text document on my desktop of possible combinations
    		//only currently a max length of 3 since I have no idea how to simulate more for loops or what not
    		//notice that 3 for loops = char length of 3
    		for(int I = 1;I<CharSplit.length;I++)
    		{
    			//takes up first character
    			Str += CharSplit[I];
    			//writes it to a file, along with a separation to the next line
    			out.write(Str + System.getProperty("line.separator"));
    			//clears Str for further use
    			Str = "";
    			for(int O = 1;O<CharSplit.length;O++)
    			{
    				//writes 2 pieces into Str for a 2 char length
    				Str += CharSplit[I] + CharSplit[O];
    				//writes to file along with a new line
    				out.write(Str + System.getProperty("line.separator"));
    				//clears Str
    				Str = "";
    				for(int P = 1;P<CharSplit.length;P++)
    				{
    					//writes 3 pieces into Str for a 3 char length
    					Str += CharSplit[I] + CharSplit[O] + CharSplit[P];
    					//writes to file along with new line
    					out.write(Str + System.getProperty("line.separator"));
    					//clears Str
    					Str = "";
    				}
    			}
    		}
    		//closes the file writing stream
            out.close(); 
    	}
    }
    /*
    How can I simplify the for loops so that they are more customizable?
    Ex:
    A variable called Length controls the maximum length, no need to paste in new for loops
    */
    As you can see, it's rediculasly long and hard to change the length. Does anyone have any idea how to simplify this into say, one for loop able to be changed on a variable? What would I have to do? I'm very completely stumped.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You can't do it in only one loop but you can make it more dynamic.

    Something along the lines of this
    Code:
    pw = initial pw
    output pw
    
    loop until length of pw exceeds max length
       increment first character of pw
    
       loop through each character in pw
          if character is beyond last allowable character
             reset to first character
             increment next character
          else 
             exit loop
          end if
       end loop
    
       ouput pw
    end loop
    Last edited by Rabbit; Apr 7 '12, 03:31 AM.

    Comment

    • limweizhong
      New Member
      • Dec 2006
      • 62

      #3
      Just a correction to the above post, when you "loop through each character in pw", and reach the last character, and this last "character is beyond last allowable character", you need to add a new character, the first allowable character, to the back of pw, instead of "incrementi ng next character".

      I probably would not do it the above way though. I would implement a simple recursive solution - create a new function that (1) prints the current string (2) (if string is not at maximum length) goes through all possible characters to add to the end of the string and calls itself recursively. This is the pseudo-code in JavaScript:
      Code:
      var str="",acceptable_chars="abcd",max_length=4,allstr=[];
      function printLn(str)
      {
          allstr.push(str);
      }
      function makestr()
      {
          printLn(str); // generic print function
          if( str.length==max_length ) return;
          for(var a=0;a<acceptable_chars.length;a++)
          {
              str+=acceptable_chars.charAt(a); // add a possible last character
              makestr();
              str=str.slice(0,-1); // pluck off the last character added two lines above
          }
      }
      makestr();
      alert(allstr);
      Edit: Changed function name from "do" to "makestr" as "do" is a keyword... :P.

      Edit: Earlier code crashed because "str.slice(-1)" did NOT truncate the last character of the string. It should be "str.slice( 0,-1)". Interestingly, it crashed Firefox completely when I ran it in Scratchpad.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        A recursive solution will spiral out of control. If his goal is to get all possible combinations of characters, and from his post, he wants at least 4 characters, probably more, then even if we limit to the character set available on a standard keyboard, that's 88.5 million combinations at 4 characters. Add a bunch more if you want to use the full ASCII character set. Add a ton more if you want more than 4 characters.

        Comment

        • limweizhong
          New Member
          • Dec 2006
          • 62

          #5
          Your solution also will. It's similarly exponential. If you're talking about stack space, in the recursive solution, stack space used is linear in number of characters.

          Comment

          Working...