Search code examples
javarandommethodsclass-method

How to choose a method randomly in Java


I have several sort and search methods in a class

public static void MetodoBurbuja(int[] A) {
    int i, j, aux;

    for (i = 0; i < A.length - 1; i++) {
        for (j = 0; j < A.length - i - 1; j++) {
            if (A[j + 1] < A[j]) {
                aux = A[j + 1];
                A[j + 1] = A[j];
                A[j] = aux;
            }
        }
    }
}

public static void MetodoBurbujaOptimizada(int vector[]) {
    int aux, i, j;
    for (i = 0; i < vector.length; i++) {
        for (j = 0; j < i; j++) {
            if (vector[i] < vector[j]) {
                aux = vector[j];
                vector[j] = vector[i];
                vector[i] = aux;
            }
        }
    }
}

And called them from the main class with the variable metbu.

public static void main(String[] args) throws IOException {
    
    //llamamos al metodo burbuja
    metodoburbuja2 metbu = new metodoburbuja2();

    for(int i = 0; i < ejec; i++){
    
        int [] inputTenThousand = new int [500000];
        int n = inputTenThousand.length;
        for (int a = 0; a < inputTenThousand.length; a++){
        
            inputTenThousand [a] = (int) (Math.random() * 500000);
            
        }
        
        long time_start, time_end;
        time_start = System.nanoTime(); 

       metbu.MetodoBurbujaOptimizada(inputTenThousand);

        time_end = System.nanoTime();
        
        nanosec = time_end - time_start;
        milsec = nanosec * 0.000001;
        System.out.print(milsec + " ");

    }
    

How could you make one of all these methods be chosen at random?

Any criticism, help or advice, I would appreciate it as you do not have an idea


Solution

  • You can use another Math.random() statement to randomly pick between the two methods with an if statement

    So instead of just the solo call:

    metbu.MetodoBurbujaOptimizada(inputTenThousand);
    

    Try using something like:

    if(Math.random() > 0.5){
        System.out.println("Using MetodoBurbuja");
        metbu.MetodoBurbuja(inputTenThousand);
    }
    else{
        System.out.println("Using MetodoBurbujaOptimizada");
        metbu.MetodoBurbujaOptimizada(inputTenThousand);
    }
    

    Hopefully I'm interpreting your question correctly!

    As for other pointers, you can use System.currentTimeMillis() instead of nanoseconds and you won't have to convert them into milliseconds.