Calculate Square pair in array in Java


Count Square Pairs in Java based on arrays. From the array here is the name function countSquarePairs  using for calculate square pairs.

Lets first define array:

int [] sparray= new int[] {9, 0, 2, -5, 7};

then calculated square pairs from this function:


private static int countSquarePairs(int[] sparray) {
int count=0;
// TODO Auto-generated method stub
if (sparray.length<=1) {
return 0;
}
else {
//Arrays.sort(sparray);


    int i, j, temp;  //be sure that the temp variable is the same "type" as the array
    for ( i = 0; i < sparray.length - 1; i ++ ) 
    {
         for ( j = i + 1; j < sparray.length; j ++ )
         {
              if( sparray[ i ] > sparray[ j ] )         //sorting into descending order
              {
                      temp = sparray[ i ];   //swapping
                      sparray[ i ] = sparray[ j ];
                      sparray[ j ] = temp; 
               }           
         }
    }

System.out.println("---"+Arrays.toString(sparray));
for (int y = 0; y < sparray.length-1; y++) {
for (int z = y+1; z < sparray.length; z++) {
int tem=sparray[y]+sparray[z];
int square=(int)Math.sqrt(tem);
if (tem==square*square) {
count+=1;
}
}
}
}
return count;
}
Here is the final print how many square pair values in existing arrays:

System.out.println("No of countSquarePairs=="+countSquarePairs(sparray));


Output of above arrays:

No of countSquarePairs==4

Happy Coding!!!

No comments:

Post a Comment

Circle

Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace