实现一个可以在指定范围产生随机数组的函数

C/C++实现

Helper.h

#include <ctime>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <cstdio>

int* generateRandomArray(int number, int rangeLeft, int rangeRight);

Helper.cpp

#include "Helper.h"

int * generateRandomArray(int number, int rangeLeft, int rangeRight) {
    // 使用完成后应该使用delete[] xxx删除空间
    // 确保rangeLeft小于rangeRight
    assert(rangeLeft < rangeRight);
    int *arr = new int[number];
    srand(time(NULL));
    for (int i = 0; i < number; i++) {
        // 生成随机数
        // rand()函数生成0到最大整数的随机数
        arr[i] = rand() % (rangeRight - rangeLeft + 1) + rangeLeft;
    }
    return arr;
}

main.cpp

#include "Helper.h"
int main() {
    int* arr = generateRandomArray(10, 8, 12);
    delete[] arr;
}

Java实现

Helper.java

import java.util.Random;

public class Helper {
    public static int[] generateRandomArray(int number, int rangeLeft, int rangeRight) {
        int[] arr = new int[number];
        Random random = new Random();
        for (int i = 0; i < number; i++) {
            arr[i] = (random.nextInt(Integer.MAX_VALUE)) % (rangeRight - rangeLeft + 1) + rangeLeft;
        }
        return arr;
    }
}

TestHelper.java

public class TestHelper {

    public static void main(String[] args) {
        int[] arr = Helper.generateRandomArray(10, 10, 20);
        for (int i = 0; i < 10; i++) {
            System.out.println(arr[i]);
        }
    }
}
点赞