reggiw
reggiw

Reputation: 77

unique vector with random numbers

My program is to write a c++ program initializes an integer vector v of size SIZE with distinct random integers each in a range [0,2*SIZE], how can I ensure all of my numbers in the vector are unique how can I edit my initialize vector so that it works properly, something in my logic is flawed. Shuffle cannot be used.

#include <iostream>
#include <ctime>
#include <vector>
#include <iomanip>
#include<algorithm>

const int SIZE =10;
unsigned int seed = (unsigned)time(0);
using namespace std;

double random (unsigned int &seed);
void print_vector (vector<int> :: iterator b,
                   vector<int> :: iterator e );
void initialize_vector(vector<int> &v);
vector<int>v;

int main()
{
    cout << endl;
    initialize_vector(v);
    cout << "Vector : " << endl;
    print_vector(v.begin(), v.end());
    return 0;
}

double random(unsigned int &seed)
{
    const int MODULUS = 15749;
    const int MULTIPLIER = 69069;
    const int INCREMENT = 1;
    seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
    return double (seed)/MODULUS;
}

void initialize_vector(vector<int> &v)
{
    vector<int> used;
    int count_unused, k;
    for (int i=0; i<2*SIZE; i++)
    {
        used.push_back(0);
    }
    for (int i=0; i<SIZE; i++)
    {
        int j= (random(seed)*(2*SIZE+1-i)) + 1;
        count_unused = 0;
        k = 0;
        while (count_unused != j)
        {
            if (used[k] == 0)
                count_unused++;
            k++;
        }
        used[k] = 1;
        v.push_back(j);
    }

}

void print_vector (vector<int> :: iterator b,
                   vector<int> :: iterator e )
{
    vector<int> :: iterator p =b;
    while(p<e)
        cout << setw(3) << (*p++);
    cout << endl;
}

Upvotes: 2

Views: 936

Answers (3)

Jonathan Mee
Jonathan Mee

Reputation: 38919

As mentioned by sv90 in the absence of shuffle, or with very large SIZEs you may prefer an unordered_set to ensure unique numbers. Initialize this unordered_set with a uniform_int_distribution and then initialize your vector with this unordered_set. Something like this:

unordered_set<int> initialize_vector;
mt19937 g{ random_device{}() };
const uniform_int_distribution<int> random{ 0, SIZE };

while(size(initialize_vector) < SIZE) {
  initialize_vector.insert(random(g));
}

const vector<int> v{ cbegin(initialize_vector), cend(initialize_vector) };

Live Example

Upvotes: 0

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

Ok, here is the solution without any storage and checks based on Reservoir Sampling. We emulate stream with values from 0 to 2*SIZE inclusively, and fill reservoir with equal probabilities. No need to prefill and then erase data, one-pass sampling. NO SHUFFLE! Code, Visual C++ 2019

#include <iostream>
#include <vector>
#include <random>

constexpr int SIZE = 10;
constexpr int EOS = -1; // end-of-stream marker

static int s = 0;

void init_stream() {
    s = 0;
}

int next_stream() {
    if (s > 2 * SIZE)
        return EOS;
    return s++;
}

std::mt19937_64 rng{ 1792837ULL };

int random(int lo, int hi) {
    std::uniform_int_distribution<int> ud{ lo, hi };
    return ud(rng);
}

std::vector<int> reservoir(int size) {
    std::vector<int> r(size, 0);
    auto v = next_stream(); // value from stream
    for (int k = 0; v != EOS; ++k, v = next_stream()) {

        if (k < r.size()) { // fill reservoir
            r[k] = v;
        }
        else { // replace elements with gradually decreasing probability
            unsigned int idx = random(0, k);
            if (idx < r.size()) {
                r[idx] = v;
            }
        }
    }
    return r;
}

int main() {
    std::vector<int> h(2*SIZE+1, 0);

    for (int k = 0; k != 100000; ++k) {
        init_stream();
        std::vector<int> r{ reservoir(SIZE) };
        for (auto v : r) {
            h[v] += 1;
        }
    }

    for (auto v : h) {
        std::cout << v << '\n';
    }

    return 0;
}

Printed histogram shows quite uniform distribution.

Upvotes: 1

YSC
YSC

Reputation: 40060

std::iota and std::random_shuffle1 do the trick:

constexpr int SIZE = 10;
std::vector<int> values(2*SIZE+1);
std::iota(begin(values), end(values), 0);
std::random_shuffle(begin(values), end(values));
values.resize(SIZE);

Full demo: http://coliru.stacked-crooked.com/a/0caca71a15fbd698

How it works?

First, a vector of 2*SIZE+1 is created...

std::vector<int> values(2*SIZE+1);

... and filled with consecutive integers from 0 to 2*SIZE.

std::iota(begin(values), end(values), 0);

We shuffle those values...

std::random_shuffle(begin(values), end(values));

... and remove the second useless half.

values.resize(SIZE);

Voila.


1) Notice: this is a C++11/14 solution as std::random_shuffle is deprecated since C++14 and removed in c++17.

Upvotes: 5

Related Questions