jeudi 28 mars 2019

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 allof 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.

#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;
}




Aucun commentaire:

Enregistrer un commentaire