1. 程式人生 > >實現一個可以在指定範圍產生隨機陣列的函式

實現一個可以在指定範圍產生隨機陣列的函式

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