微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Java中随机选择一个方法

如何解决如何在Java中随机选择一个方法

我在一个类中有几种排序和搜索方法

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;
            }
        }
    }
}

并使用变量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 + " ");

    }
    

你怎么能随机选择所有这些方法之一?

任何批评,帮助或建议,我将不胜感激,因为您没有想法

解决方法

您可以尝试的一件事是生成一个介于 1 和要在 for 循环中运行的算法数量之间的随机数,然后在“switch”语句中使用该数字:

package com.company;

import java.util.Random;

public class Main {
    private Random randomGenerator = new Random();
    
    public static void main(String[] args) {
        // this code would go inside your for-loop:
        int randNumber = randomGenerator.nextInt(10);
        switch(randNumber) {
            case 1:
                // call method "a" here
                break;
            case 2:
                // call method "b" here
                break;
            // and so forth
            default:
                break;
        }
    }
}
,

您可以使用另一个 Math.random() 语句通过 if 语句在两种方法之间随机选择

所以,而不仅仅是单独通话:

metbu.MetodoBurbujaOptimizada(inputTenThousand);

尝试使用类似的东西:

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

希望我能正确解释您的问题!

至于其他指针,您可以使用 System.currentTimeMillis() 而不是纳秒,您不必将它们转换为毫秒。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。