简体   繁体   中英

Analysis of execution frequency code

I was trying to find out the frequency of execution of some statements in the following code.
I wanted to check how many times each for loop was executed for a given input array.

For this purpose,I added three variables icnt , jcnt and kcnt .

public class FreqCounter{

    public static void count1(int[] a){
        int N = a.length;
        int count = 0;
        int icnt = 0;
        int jcnt = 0;
        int kcnt = 0;
        for(int i=0;i<N;i++){
            icnt++;
            for(int j=i+1;j<N;j++){
                jcnt++;
                for(int k=j+1; k<N;k++){
                    kcnt++;
                }
            }
        }

        System.out.printf("i loop=%d times\n",icnt);
        System.out.printf("j loop=%d times\n",jcnt);
        System.out.printf("k loop=%d times\n",kcnt);
    }

    public static void main(String[] args) {
        int N = 100;
        int[] a =  new int[N];
        count1(a);
    }
}

I got the following output

i loop=100 times
j loop=4950 times
k loop=161700 times

I tried to analyze this as follows

  1. The outer for loop (i=0 to < N)

    This executes N times ,so for N=100 ,the count will be 100

  2. Inner for loop(j=i+1 to < N)

    This is equivalent to finding combinations of N elements ,taken 2 at a time

    which means C(N,2) = N! /((N-2)! * 2!) = (N *(N-1))/2 = ((N^2)/2)-(N/2) C(N,2) = N! /((N-2)! * 2!) = (N *(N-1))/2 = ((N^2)/2)-(N/2)

    For N=100 , this will be (100*100/2)-50 = 4950

  3. Innermost loop (k=j+1 to < N)

    Equivalent to finding combinations of N elements ,taken 3 at a time

    ie, C(N,3) = N!/((N-3)! * 3!) = N*(N-1)*(N-2)/3! = (N^3/6)-(N^2/2)+N/3 C(N,3) = N!/((N-3)! * 3!) = N*(N-1)*(N-2)/3! = (N^3/6)-(N^2/2)+N/3

    For N=100 , this will be 100^3/6 - 100^2/2 + 100/3 = 161700

I am getting the correct values,but wanted to know if the analysis(combinations stuff) is proper.(I have only recently learned the permutation/combinations lessons).If someone can add more to this analysis, it would be helpful.

Your combinatorics is perfectly fine, you have n distinct elements, and you need the number of possibilities to chose 3 elements, order does not matter, no repeats. This is indeed C(N,3) .

(Disclaimer, I was a combinatorics TA during the last months)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM