生成随机数并存储到数组然后检查相同的新随机数

时间:2016-02-20 08:36:20

标签: java random

我生成了1-10个随机数并将其存储在一个数组中。我的问题是我将如何首先编码,随机三次,如果2或全部重复,然后再次随机三次,如果它们彼此不同,则保存到数组。所以这是我的代码:

  class base_test extends uvm_test;
    ........
    ........
    virtual function void set_registerA(....);
        regs.registerA1.set(....);
        regs.registerA2.set(....);
        regs.registerA3.set(....);
    endfunction

    virtual function void set_registerB(....);
        regs.registerB1.set(....);
        regs.registerB2.set(....);
        regs.registerB3.set(....);
    endfunction

   task main_phase (uvm_phase phase)
   // Copy your run_phase code over here
   endtask : main_phase

 endclass

class test1 extends base_test;
    virtual task configure_phase(uvm_phase phase);
        set_registerA(....);
        set_registerB(....);
    endtask

    virtual task main_phase(uvm_phase phase);
        super.main_phase(phase);
    endtask : main_phase
endclass

class test2 extends base_test;
    virtual task configure_phase(uvm_phase phase);
        set_registerA(....);
        set_registerB(....);
    endtask : configure_phase

    virtual task main_phase(uvm_phase phase);
        super.main_phase(phase);
    endtask : main_phase
endclass

3 个答案:

答案 0 :(得分:0)

您可以检查数组是否包含此随机数。

Arrays.asList(arr).contains(randomNum)

如果没有,那么你将它添加到数组中,否则抛出异常或忽略取决于你的逻辑。

我认为类似的问题:How can I test if an array contains a certain value?

答案 1 :(得分:0)

public boolean checkArray(Int[] arr, Int targetValue) {
    for(Int i: arr){
        if(i == targetValue)
            return true;
    }
    return false;
}

答案 2 :(得分:0)

我认为这就是你要找的东西:

public static int[] generatePureRandomIntegers(int n) {
    final int[] array = new int[n];
    for (int i = 0; i < n; i++) {
        array[i] = i + 1;
    }
    final Random random = ThreadLocalRandom.current();
    for (int i = array.length; i > 1; i--) {
        swap(array, i - 1, random.nextInt(i));
    }
    return array;
}

private static void swap(int[] array, int i, int j) {
    int tmp = array[i];
    array[i] = array[j];
    array[j] = tmp;
}

创建一个新的int数组,并将其从1填充到n,然后将数组洗牌。

例如:

int[] randomNumbers = generatePureRandomIntegers(10);
System.out.println(Arrays.toString(randomNumbers)); // [4, 6, 5, 7, 1, 10, 8, 9, 2, 3]