如何检查随机值中的重复项并在循环中返回值

问题描述 投票:0回答:1

我想创建一个随机函数来生成随机值并将其返回并将其存储在数组中,但应避免重复值

int random_function() {
    const int size = 80;
    int arr[80];
    int i = 1;

    srand(time(0));
    int session = 0;
    for (i = 1; i < size; i++) {
        session = rand();
        session = arr[i] for (int j = 1; j < i; j++) {
            if (arr[j] == arr[i]) {
                i--;
            }
        }
        return session
    }

    return -1;
}
c++
1个回答
0
投票

由于您的函数需要记住之前 80 个生成的数字,以避免返回其中之一,因此您可以创建数组

static
并保留一个
static
索引,在其中为每次调用写入新数字。

这是一个例子:

#include <algorithm>
#include <array>
#include <ctime>
#include <iostream>
#include <random>

int random_function() {
    static std::array<int, 80> arr = [] {
        std::array<int, 80> rv;
        rv.fill(-1);  // can't be returned by `rand`
        return rv;
    }();
    static unsigned idx = 0;

    int session;
    do {
        session = rand();
        // check if the generated number is among the 80 last generated
        // and if it is, try again:
    } while (std::find(arr.begin(), arr.end(), session) != arr.end());

    arr[idx] = session;           // store the number
    idx = (idx + 1) % arr.size(); // and step the index before the next call

    return session;
}

int main() {
    srand(time(0));
    for (int i = 0; i < 80; ++i) {
        std::cout << random_function() << '\n'; // 80 unique numbers
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.