1

this is what i have of the function so far. This is only the beginning of the problem, it is asking to generate the random numbers in a 10 by 5 group of numbers for the output, then after this it is to be sorted by number size, but i am just trying to get this first part down.

/* Populate the array with 50 randomly generated integer values
* in the range 1-50. */
void populateArray(int ar[], const int n) {
    int n;
    for (int i = 1; i <= length - 1; i++){

        for (int i = 1; i <= ARRAY_SIZE; i++) {
            i = rand() % 10 + 1;
            ar[n]++;
        }

    }
}
1
  • 2
    Please compile with maximum warning level. If you do so, your compiler should warn you that you are declaring a local variable n when another variable n already exists (you are thus hiding the parameter n). And you are using this uninitialized n in your line "ar[n]++". Also: what is length? What is ARRAY_SIZE? What is n supposed to be? Commented Oct 28, 2014 at 16:54

1 Answer 1

1

First of all we want to use std::array; It has some nice property, one of which is that it doesn't decay as a pointer. Another is that it knows its size. In this case we are going to use templates to make populateArray a generic enough algorithm.

template<std::size_t N>
void populateArray(std::array<int, N>& array) { ... }

Then, we would like to remove all "raw" for loops. std::generate_n in combination with some random generator seems a good option.

For the number generator we can use <random>. Specifically std::uniform_int_distribution. For that we need to get some generator up and running:

std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<> dist(1, N);

and use it in our std::generate_n algorithm:

std::generate_n(array.begin(), N, [&dist, &generator](){ 
    return dist(generator); 
});

Live demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the feedback, but the only problem with this is i was given main and all the functions already, we have to build the functions accordingly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.