1 2 3
1 3 2
2 3 1
2 1 3
3 1 2
3 2 1
write a Java program to print out the pattern
Answers
Patterns in Java
Here we have an interesting pattern which shows all the permutations of 3 distinct digits: 1, 2 and 3.
Our usual analysis of running a loop for 6 rows doesn't really fit well here.
Here we must see that we must keep three variables, run each of them from 1 to 3 and print the numbers only when they are all distinct.
Here is a Java program which prints the pattern:
public class Pattern
{
public static void main(String[] args)
{
/* We need three variables: i, j, k. Each runs from 1 to 3.
* We will print a triplet (i,j,k) only if all of them are distinct
*/
for(int i=1;i<=3;i++) //Loop of i
{
for(int j=1;j<=3;j++) //Loop of j
{
if(i==j) //If i equals j, then we continue the j loop without going into the k loop
continue;
for(int k=1;k<=3;k++) //Loop of k. Executes only if i and j are distinct
{
//If k equals any of i or j, then we continue without executing the print statement
if(j==k || i==k)
continue;
System.out.println(i+" "+j+" "+k); //Printing the triplet (i,j,k)
}
}
}
}
}