I have an std::vector with fixed size N = 5. I want every element of the vector to be randomly selected between two positive numbers, in particular 1 and 12. (zeros are not allowed).Each element should be unique on the vector.
Code so far:
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
constexpr int MAX = 20;
constexpr int LINES = 5;
int sum{};
int maxNum = 12;
int minNum = 1;
std::array<int, LINES> nums;
for (int i = 0; i < LINES; ++i) {
maxNum = std::min(maxNum, MAX - sum);
minNum = std::min(maxNum, std::max(minNum, MAX - maxNum * (LINES - i)));
std::cout << minNum << " " << maxNum << std::endl;
std::uniform_int_distribution<> dist(minNum, maxNum);
int num = dist(gen);
nums[i] = num;
sum += num;
}
std::shuffle(std::begin(nums), std::end(nums), gen);
std::copy(std::begin(nums), std::end(nums), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
}
Aucun commentaire:
Enregistrer un commentaire