So I'm trying to find a way to basically generate 100 numbers from 0 to 99 in random order with no duplicates. This is my code, and as you can see it displays 100 numbers but....some are duplicates.

srand((unsigned)time(0));
for (int count = 0; count < 100; count++)
{
int y;

y = (rand()%100)+1;
cout<<y<<endl;


}

Dani AI

Generated

The duplicates you saw are expected: calling rand() repeatedly can return the same value more than once, and your +1 makes the range 1..100 instead of 0..99. was right to suggest producing a permutation rather than retrying until you get 100 distinct hits, and is right that loop control matters if you try rejection sampling.

A compact, modern C++ solution is to create the ordered list 0..99, then shuffle it once with a proper engine. The result is a uniform permutation with no duplicates:

#include <algorithm>
#include <numeric>
#include <random>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> nums(100);
    std::iota(nums.begin(), nums.end(), 0);        // fills 0..99
    std::random_device rd;
    std::mt19937 gen(rd());
    std::shuffle(nums.begin(), nums.end(), gen);
    for (int n : nums) std::cout << n << '\n';
}

Why this is better: it guarantees each value appears exactly once, avoids the cost of repeated duplicate checks, and uses the C++11+ <random> facilities instead of rand()/srand(), which suffer from poor quality and modulo bias. For details on the recommended APIs see and the C++ random utilities at cppreference.

If only a subset of unique values is needed (k < 100), consider std::sample (C++17) or a partial Fisher–Yates approach to avoid shuffling the whole range. For deterministic runs (tests, debugging) seed mt19937 with a fixed integer instead of std::random_device.

Recommended Answers

All 2 Replies

You could allocate an array of 1 to 100, then shuffle it.

Or, as you generate a new number, scan the current array content looking for duplicate, reject the number if found. But that becomes a time consuming operation, the more full the array gets. I'd go with the first option.

Just to add one quick thing: use a while loop instead so that you can exit when you have 100 numbers not just when you've gone through the cycle 100 times (I suppose you could rework your for loop to accomplish the same thing too but it might be more difficult to read).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.