Monday, June 13, 2016

Check Single Swap Array in Java

Here is the code :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
 public static boolean CheckSingleSwap(int[] A)
 {
  int count = 0;
  int[]B = Arrays.copyOf(A, A.length); 
  Arrays.sort(B);  
  for(int i=0; i<A.length; i++)
  {
   if(A[i] != B[i]) count++;
  }
  
  if(count > 2) return false;
  return true;
 }

Test case :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
System.out.println("Test Single Swap for Array...");
 int[]A = {1,2};
     int[]B = {1,3,6,3,5,5,3,7,7};
     int[]C = {1, 4, 5, 6, 7, 2}; 
     int[]D = {1,2,3,4,5,6,7,8,9,10,11,2,45,56,67,78,89,90,123,124,1245566778};
     int[]D1 = {1,2,3,4,5,6,7,8,9,10,11,2,45,56,67,78,89,90,2,123,124,1245566778};
     int[]E = {1, 5, 3, 3, 7} ;
     int[]F= {1, 3, 5};
     int[]G = {1,5,3};
     int[]H = {1, 2, 6, 3, 4, 5};

     System.out.println("A : "+CheckSingleSwap(A));
     System.out.println("B : "+CheckSingleSwap(B));
     System.out.println("C : "+CheckSingleSwap(C));
     System.out.println("D : "+CheckSingleSwap(D));
     System.out.println("D1 : "+CheckSingleSwap(D1));
     System.out.println("E : "+CheckSingleSwap(E));
     System.out.println("F : "+CheckSingleSwap(F));
     System.out.println("H : "+CheckSingleSwap(H));

Output :
1
2
3
4
5
6
7
8
A : true
B : true
C : false
D : false
D1 : false
E : true
F : true
H : false


No comments:

Post a Comment