Saturday 16 March 2013

Generate all combinations by java Program



Generate all combinations by java Program

In this post we are going to brief you, how to disclose all combination of passwords or you want all combinations of some numbers or words or characters  for some programming or gaming logic this is the best function we think can be used for. As usual before going to source code, simple intro to combinations and permutations :)

 it's few points to be noted:
If the order does matter it is a Permutation and order doesn't its Combinations.

What's the Difference?
In English we use the word "combination" loosely, without thinking if the order of things is important. In other words:

"My fruit salad is a combination of apples, grapes and bananas" We don't care what order the fruits are in, they could also be "bananas, grapes and apples" or "grapes, apples and bananas", its the same fruit salad.
   
"The combination to the safe was 472". Now we do care about the order. "724" would not work, nor would "247". It has to be exactly 4-7-2.
So, in Mathematics we use more precise language:
If the order doesn't matter, it is a Combination.
If the order does matter it is a Permutation.
Now what we brief here is a solution for this  :
"Generate  all combination of '123456asdqwezxc' of lenth=3, with out repetation"



  private void permutation(String prefix, String str,int length) {
        int n = str.length();
        if (prefix.length()==length) {
            System.out.println(prefix);
        } else {
            for (int i = 0; i < n; i++) {
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n),length);
            }
        }
  }

for our solution we call this method like this:  permutation("", "123456asdqwezxc",3) 


And the result is:


run:
123
124
125
126...


No comments:

Post a Comment