產生 N 個互不相同的隨機整數,範圍 [0, N-1],用於測試演算法輸入資料。
a[N] 為 -1(標記未填入)。count = 0 記錄已填入個數。count == N:
temp = rand() % N。a[0..count-1],若 temp 已存在 → 丟棄,重試。a[count] = temp,count++。#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NUM 10
void random_n(int a[], int n);
int main() {
int a[MAX_NUM], i = 0;
while (i < MAX_NUM) a[i++] = -1; // 關鍵初始化
random_n(a, MAX_NUM);
for (i = 0; i < MAX_NUM; ++i)
printf("%d\t", a[i]);
printf("\n");
return 0;
}
void random_n(int a[], int n) {
int temp, j, count = 0, flag;
srand((unsigned)time(NULL));
while (count < n) {
temp = rand() % n;
flag = 0;
for (j = 0; j < count; ++j) {
if (a[j] == temp) { flag = 1; break; }
}
if (!flag) {
a[count++] = temp;
}
}
}
當 N 較大(如 10⁵)時,重複檢查極慢。下一篇將介紹 O(N) 時間、雙陣列「洗牌法」,以空間換時間,彻底解決重複檢查瓶頸。
srand(time(0)) 僅呼叫一次,放在函式開頭或 main。rand() % n 有模數偏差(非均勻),嚴格場景需用拒絕採樣或 random() / C++11 <random>。