You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保生成的0-11范围的10个数组随机元素互不重复?

Fixing Your Unique Random Number Generation Issue

Hey there! Let's break down what's going wrong with your current approach, then walk through two reliable solutions to generate 10 unique random integers between 0 and 11.

What's Wrong With Your Current Code?

Your current method has two big flaws that prevent it from working correctly:

  1. Limited duplicate checking: You only compare each element with the one immediately before it (Numbers[u] == Numbers[u-1]). This misses duplicates that are non-adjacent (like if the 0th and 5th elements are the same).
  2. Unsafe duplicate correction: When you increment/decrement a duplicate value, you don't re-check if the new value is already present in the array. This can easily create new duplicates (e.g., if you change 1 to 2, but 2 is already in the array somewhere else).

Solution 1: Fisher-Yates Shuffle (Most Efficient for This Case)

Since you're selecting almost all values from a small range (12 total values, picking 10), the Fisher-Yates shuffle is perfect. We start with a full list of 0-11, shuffle it randomly, then take the first 10 elements. This guarantees no duplicates by design.

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <algorithm> // For std::swap

using namespace std;

int main() {
    // Create a pool of all possible values (0 to 11)
    int value_pool[12];
    for (int i = 0; i < 12; ++i) {
        value_pool[i] = i;
    }

    srand(time(NULL));
    // Fisher-Yates shuffle to randomize the pool
    for (int i = 11; i > 0; --i) {
        int random_index = rand() % (i + 1);
        swap(value_pool[i], value_pool[random_index]);
    }

    // Extract the first 10 unique values
    int Numbers[10];
    cout << "Generated unique random numbers:\n";
    for (int i = 0; i < 10; ++i) {
        Numbers[i] = value_pool[i];
        cout << Numbers[i] << endl;
    }

    return 0;
}

Solution 2: Generate and Check for Duplicates

If you prefer a more straightforward approach (great for understanding the logic), you can generate a random number, check if it's already in the array, and re-generate if it is.

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

// Helper function to check if a number is already in the array
bool isDuplicate(int num, int arr[], int current_size) {
    for (int i = 0; i < current_size; ++i) {
        if (arr[i] == num) {
            return true;
        }
    }
    return false;
}

int main() {
    int Numbers[10];
    srand(time(NULL));

    cout << "Generated unique random numbers:\n";
    for (int i = 0; i < 10; ++i) {
        int new_num;
        // Keep generating until we find a number not already in the array
        do {
            new_num = rand() % 12;
        } while (isDuplicate(new_num, Numbers, i));

        Numbers[i] = new_num;
        cout << Numbers[i] << endl;
    }

    return 0;
}

Why These Solutions Work

  • Fisher-Yates Shuffle: We start with a guaranteed set of unique values, so shuffling just rearranges them—no duplicates possible. This is the most efficient method when you're selecting most values from a small range.
  • Generate-and-Check: Every new number is validated against all previously added values, ensuring we only add unique entries. While simple, it can have more repeated generation attempts if you're picking almost all values from a small range (but it still works perfectly here).

内容的提问来源于stack exchange,提问作者Default99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:43:26