473,387 Members | 1,742 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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.
Expand|Select|Wrap|Line Numbers
  1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. import java.io.OutputStreamWriter;
  4.  
  5. public class Generate {
  6.     public static void Gen() throws IOException
  7.     {
  8.         //opens a file writing stream
  9.         FileOutputStream fos = new FileOutputStream("C:\\Users\\Ryan\\Desktop\\test.txt"); 
  10.         OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
  11.         //the character list I'm using
  12.         String CharList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  13.         //gets a list of characters
  14.         String[] CharSplit = CharList.split("");
  15.         String Str = "";
  16.         //generates text document on my desktop of possible combinations
  17.         //only currently a max length of 3 since I have no idea how to simulate more for loops or what not
  18.         //notice that 3 for loops = char length of 3
  19.         for(int I = 1;I<CharSplit.length;I++)
  20.         {
  21.             //takes up first character
  22.             Str += CharSplit[i];
  23.             //writes it to a file, along with a separation to the next line
  24.             out.write(Str + System.getProperty("line.separator"));
  25.             //clears Str for further use
  26.             Str = "";
  27.             for(int O = 1;O<CharSplit.length;O++)
  28.             {
  29.                 //writes 2 pieces into Str for a 2 char length
  30.                 Str += CharSplit[i] + CharSplit[O];
  31.                 //writes to file along with a new line
  32.                 out.write(Str + System.getProperty("line.separator"));
  33.                 //clears Str
  34.                 Str = "";
  35.                 for(int P = 1;P<CharSplit.length;P++)
  36.                 {
  37.                     //writes 3 pieces into Str for a 3 char length
  38.                     Str += CharSplit[i] + CharSplit[O] + CharSplit[P];
  39.                     //writes to file along with new line
  40.                     out.write(Str + System.getProperty("line.separator"));
  41.                     //clears Str
  42.                     Str = "";
  43.                 }
  44.             }
  45.         }
  46.         //closes the file writing stream
  47.         out.close(); 
  48.     }
  49. }
  50. /*
  51. How can I simplify the for loops so that they are more customizable?
  52. Ex:
  53. A variable called Length controls the maximum length, no need to paste in new for loops
  54. */
  55.  
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.
Apr 7 '12 #1
4 7512
Rabbit
12,516 Expert Mod 8TB
You can't do it in only one loop but you can make it more dynamic.

Something along the lines of this
Expand|Select|Wrap|Line Numbers
  1. pw = initial pw
  2. output pw
  3.  
  4. loop until length of pw exceeds max length
  5.    increment first character of pw
  6.  
  7.    loop through each character in pw
  8.       if character is beyond last allowable character
  9.          reset to first character
  10.          increment next character
  11.       else 
  12.          exit loop
  13.       end if
  14.    end loop
  15.  
  16.    ouput pw
  17. end loop
Apr 7 '12 #2
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 "incrementing 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:
Expand|Select|Wrap|Line Numbers
  1. var str="",acceptable_chars="abcd",max_length=4,allstr=[];
  2. function printLn(str)
  3. {
  4.     allstr.push(str);
  5. }
  6. function makestr()
  7. {
  8.     printLn(str); // generic print function
  9.     if( str.length==max_length ) return;
  10.     for(var a=0;a<acceptable_chars.length;a++)
  11.     {
  12.         str+=acceptable_chars.charAt(a); // add a possible last character
  13.         makestr();
  14.         str=str.slice(0,-1); // pluck off the last character added two lines above
  15.     }
  16. }
  17. makestr();
  18. alert(allstr);
  19.  
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.
Apr 7 '12 #3
Rabbit
12,516 Expert Mod 8TB
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.
Apr 7 '12 #4
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.
Apr 7 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

36
by: rbt | last post by:
Say I have a list that has 3 letters in it: I want to print all the possible 4 digit combinations of those 3 letters: 4^3 = 64 aaaa
3
by: Jonathan | last post by:
Hi all! For a match schedule I would like to find all possible combinations of teams playing home and away (without teams playing to themselves of course). I now the simple version works...
16
by: akameswaran | last post by:
Ok, this is really irritating me. I'm sure there are different ways of doing this - I'm interested in the algo, not the practical solution, I'm more trying to play with iterators and recursion. I...
4
by: Suzie1986 | last post by:
Hiya, I am a newcomer to programming and really stuck!!! Any help would be gratefully received!! I have written a program that gives me all possible combinations for 1 and 2 for a length of...
2
by: stephenvr | last post by:
Calling on all the mathematical gurus out there. I am looking for a way to automate the process of working out certain possible combinations available for a number of fields, i.e. if I had 1 row of...
15
by: Alex72 | last post by:
I'm programming with C on Linux to get all possible combinations of particular sequence related to biology. But I don't know how I implement it because it seems to be very complicated to make rule....
3
by: DarkSoul | last post by:
I have multiple ArrayLists, could be 2 or 3 or 10 lists, with multiple values in them. Now what I need to do is to get a combination of all of them. For example, if I have 3 lists with the...
4
by: RSH | last post by:
Okay my math skills aren't waht they used to be... With that being said what Im trying to do is create a matrix that given x number of columns, and y number of possible values i want to generate...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.