Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
This question is a variation of a question that I posted earlier, "Print Permutations of an Array or String". The code that I had written there will not work if we have repetitions in the array.
This post is to write the code to print all the permutations, even when there are duplications in the array.
For example, If the array is {1, 2, 3} then the result should be
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1But if the array is {1, 2, 2} then the output should be
1 2 2 2 1 2 2 2 1
If there are no duplicates, the code to print permutations of an array is as below (written in Java):
/** Recursive function to print all permutations of an Integer array.
* arr: Array of integers.
* n: Number of elements in the array.
* x: Current Index of the Array.
**/
Void permutation (int[] a, int n, int x)
{
if(x == n-1)
prinArray(a);
for (int i=x; i<n; i++)
{
swap(a, i, x );
permutation ( arr, n , x+1);
swap(a, i, x );
}
}
Where printArray function prints the entire array, and the swap function swaps two elements of the array at the given indices.
Wrong Solution
If we have duplicates in the array, then we just need to keep a check of not to swap two elements if they are same. so just one extra check in the for loop:
/** Recursive function to print all permutations of an Integer array.
* arr: Array of integers.
* n: Number of elements in the array.
* x: at any given point where we are.
**/
void permutation (int[] a, int n, int x)
{
if(x == n-1)
printArray(a, n);
for (int i=x; i<n; i++)
{
if(i!= x && a[i] == a[x])
continue;
swap(a, i, x );
permutation ( a, n , x+1);
swap(a, i, x );
}
}This solution will not work because it will put 2 in the first position twice for array {1, 2, 2} (swap 1 with the first 2 and then with the second 2, because in both the cases 2 is not equal to 1). What we actually want is to make sure the 2 is placed in the first position only once.
Right Solution
The correct way is to use a Set and make sure that one value is placed at one position only once.
void permutation (int[] a, int n, int x)
{
if(x == n-1)
printArray(a, n);
HashSet set = new HashSet();
for (int i=x; i
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment