Array allocator with random number generator...

Hello. I was doing a challenge problem from my textbook...
The problem states, "Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate. The function should return a pointer to the array."

I have a few restrictions with this... I need to fill an array with random integers by using default_random_engine and uniform_int_distribution. Also, cannot use global variables.

I have written a code...it is very skeletal... I know it does not make sense. I have a vague idea of what to do, but I do not know how to do it exactly. Can you please help me? Please pardon my weird codes, if they bother you so much. Thanks :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <iomanip>
#include <random>
using namespace std;

struct getArray
{
    int *number;
    
    if (num <=0)
        return NULL;
    
    numbers = new int[num];
    return number;
    
};

struct randomNumber
{
    int number = "1234567890";
    default_random_engine rng(time(nullptr_t));
    uniform_int_distribution<size_t> dist(0, number.size() - 1);
    
};

int main()
{
    int *pointer = NULL;
    cout << " How many items are you going to enter? " << endl;
    int input;
    cin >> input;

    pointer = new int[input];
    
    
    for(int counter = 0; counter < input; counter++)
    {
        cout << " Enter the item" << counter+1;
        cin >> randomNumber;
        *(pointer+counter) = randomNumber;
    }
    
    cout << " \n The item you've entered are: ";
        for(int counter = 0; counter < input; counter++)
        {
            cout << counter+1 " item is " << *(pointer+counter) << endl;
            
        }
    
    delete []pointer;

    return 0;
}
Last edited on
In hopes of not interfering with what you learn from your college, I suggest you use a simpler approach to the random number generator:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    int x;
    srand(time(NULL));
    x = rand();
}


This can generate any number that can be stored inside an int variable, and stores it into x, i.e. x can have any value in the set [0, max_int).

If you want to set bounds to your number, then you can do this:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    int x, lower_bound, upper_bound;
    srand(time(NULL));
    x = lower_bound +(rand() % (upper_bound - lower_bound));
}


This generates any integer number in the set [lower_bound, upperbound).

After that, you can easily store the numbers in an array.
Last edited on
Topic archived. No new replies allowed.