Input:
X and Y are integer values, where X < Y
N is the length of permutation
Output:
To print all the possible permutations in sorted order, in given form, starting from zero.
i.e 0 , 0 + X (or Y)
For example:
X = 1, Y = 2
N = 3.
output should be:
0 1 2
0 1 3
0 2 3
0 2 4
To solve this problem, we can use recursion by passing the value of X and Y with the current state array.
At each recursion step, we will call the method by passing values of X or Y in order. The end of the recursion would be the length of array reaching the value of N.
Here is the code:
You can also clone the repository from GIT using the link below:
https://github.com/Niravkumar-Patel/SnippetExampleRepo.git
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.ArrayList; public class PossiblePermutations { int x=1; int y=2; int permutSize = 5; int length; public static void main(String args[]){ PossiblePermutations pd = new PossiblePermutations(); ArrayList<Integer> al = new ArrayList<Integer>(); al.add(0); pd.printAllPermutations(al); } public void printAllPermutations(ArrayList<Integer> a){ ArrayList<Integer> a1 = new ArrayList<Integer>(a); if(a.size() == permutSize){ System.out.println(a); }else{ a.add(a.get(a.size()-1) + x); printAllPermutations(a); a1.add(a1.get(a1.size()-1) + y); printAllPermutations(a1); } } public void printArray(int a[]){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(""); } } |
The output of above code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Input: X = 1 Y = 2 N = 5 Output: [0, 1, 2, 3, 4] [0, 1, 2, 3, 5] [0, 1, 2, 4, 5] [0, 1, 2, 4, 6] [0, 1, 3, 4, 5] [0, 1, 3, 4, 6] [0, 1, 3, 5, 6] [0, 1, 3, 5, 7] [0, 2, 3, 4, 5] [0, 2, 3, 4, 6] [0, 2, 3, 5, 6] [0, 2, 3, 5, 7] [0, 2, 4, 5, 6] [0, 2, 4, 5, 7] [0, 2, 4, 6, 7] [0, 2, 4, 6, 8] |
You can also clone the repository from GIT using the link below: