Question: Combine the two permutations p 1 and p 2 into a result permutation p that represents the operation of first applying permutation p 2 to

Combine the two permutations p1 and p2 into a result permutation p that represents the operation of first applying permutation p2 to the given array, followed by applying permutation p1 to this intermediate result.
public static int[] chain(int[] p1, int[] p2){
int[] p = new int[p1.length];
for (int i =0; i < p1.length; i++){
p[i]= p1[p2[i]];
}
return p;
}
// Given the permutation perm, construct its inverse permutation that, when combined with perm, produces the identity permutation for which p[i]== i for all positions i.
public static int[] inverse(int[] perm){
int[] inv = new int[perm.length];
for (int i =0; i < perm.length; i++){
inv[perm[i]]= i;
}
return inv;
}
// The square of the permutation is constructed by combining it with itself.
public static int[] square(int[] perm){
return chain(perm, perm);
}
// Compute the k-th power of the given permutation perm, that is, the result of chaining perm with itself k times.
public static int[] power(int[] perm, int k){
if (k ==0){
int[] idenPerm = new int[perm.length];
for (int i =0; i < perm.length; i++){
idenPerm[i]= i;
}
return idenPerm;
} else if (k ==1){
return perm;
} else if (k ==2){
return square(perm);
} else if (k <0){
return power(inverse(perm),-k);
} else if (k %2==0){
int[] tempPerm = power(perm, k/2);
return square(tempPerm);
} else {
int[] tempPerm = power(perm,(k-1)/2);
return chain(perm, square(tempPerm));
}
}
// Main method for testing
public static void main(String[] args){
int[] perm1={1,0,2,3};
int[] perm2={1,3,6,0,5,2,4,7};
int[] perm3={0,6,3,4,8,7,2,9,5,1};
int[] res1= power(perm1,4);
int[] res2= power(perm2,98);
int[] res3= power(perm3,-397);
// Print expected and actual results
System.out.println("Expected result for perm1,4: {0,1,2,3}");
System.out.println("Actual result: "+ Arrays.toString(res1));
System.out.println("Expected result for perm2,98: {3,0,4,1,2,6,5,7}");
System.out.println("Actual result: "+ Arrays.toString(res2));
System.out.println("Expected result for perm3,-397: {0,9,6,2,3,8,1,5,4,7}");

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!