codelop
codelop

Reputation: 64

How to fill an array with random values from a range? (Duplicates are OK.)

I am new to C++, I have a problem of array manipulation. I have an array of X with length 100, I need to fill the value of X with integer value of 1 to 10 (1,2,3,4,5,6,7,8,9,10) randomly. I know that there will be duplicate, maybe like 1 printed ten times, etc, but that's really what I want.

Here is what I have:

an array of X:

int X[100];

Here is my code snippet:

int* X = NULL;
int* val = NULL;
int length1= 100;
int length2= 10;
X = new int[length1];
val = new int[length2];
int i;
int j;

for (i = 0; i < isi; i++) {
    val[i] = i;
    for (j = 0; j < length1; j++) {
        if (j > i) {
            X[j] = val[i];
        } else {
            X[j] = val[0];
        }
        cout << "X[" << j << "] = " << X[j] << "\n";
        Sleep(1);
    }
}

Code above makes the array X from index 0 to 99 has value of 0, then index 0 to 99 has value of 1 and so the other index until the index 0 to 99 has value of 9.

This is not what I want, what I want is to make it (if it is not random) index 0 to 9 has value of 0, then 10 to 19 has value of 1 ... until index 90 to 99 has value of 9. Hope my explanation clear.

I have come to a question in stackoverflow: How would you make an array of 10000 with only values of 1-1000 inclusive?

But still can't resolve my problem my self. Can someone please give me solution to this.

Thank you in advance

Upvotes: 3

Views: 44296

Answers (5)

Arturo
Arturo

Reputation: 1

I think others have pointed it out but you have to first write the pre-compiler directive #include <ctime> and then use the srand function. Most would say don't use that but since you and I are at the basics our teachers, respectively, start us off with that. And it might work with your compiler as well. Here is a link to learn more about it. I would have commented but I can't. http://www.cplusplus.com/reference/cstdlib/srand/

Upvotes: 0

w.b
w.b

Reputation: 11228

You can also use generate function:

#include <iostream>
#include <algorithm>
#include <random>

using namespace std;

int main()
{
    int arr[100];
    random_device rd;
    default_random_engine dre(rd());
    uniform_int_distribution<int> uid(0,9);

    generate(arr, arr + sizeof(arr) / sizeof(int), [&] () { return uid(dre); });

    for (int a : arr)
        cout << a << " "; 
}

Upvotes: 8

user2864740
user2864740

Reputation: 61865

Here are two ways to solve this problem - since this is a learning experience, only pseudo code (and relevant links) are provided. Each "task" can be looked up and solved separately. Note that neither method uses a secondary array.

If the amount of each number in the final result does not need to be the same (eg. 2 might appear 17 times) then consider the following loop-and-assign-random approach. A standard C for-each loop is sufficient.

# for every index pick a random value in [0, 10) and assign it
for i in 0 to last array index:
    array[i] = random in range 0, 10

If the amount of numbers need to be the same, then consider filling the array and then shuffling it. The modulus operator is very handy here. (This assumes the array length is a multiple of the group size.)

# fill up array as 0,1,2,3,4,5,6,7,8,9,0,1,2.. (will be 10 groups)
for i in 0 to last array index:
    array[i] = i % 10
# and randomly rearrange order
shuffle array

For the shuffle see Fisher-Yates, which even shows a C implementation - there are "more C++" ways, but this is a good technique to learn and practice with loops. (One cool property about Fisher-Yates is that as soon an item is swapped into the current index it is at the final swap location - thus the shuffle loop can be modified to shuffle and immediately perform an action such as displaying the value.)

In both cases a random function should be used; else the numbers will not be .. random.

Upvotes: 5

Darren Stone
Darren Stone

Reputation: 2068

#include <stdlib.h>

int main(int argc, char **argv) {
  int r[100];
  for (int i = 0; i < 100; ++i) {
    r[i] = rand() % 10 + 1;
  }
}

For some output, you can #include <iostream> and then std::cout << "r[" << i << "] = " << r[i] << "\n" inside the loop after each assignment.

If you want to seed the random number generator for a different sequence each time, then #include <time.h> and then srand(time(NULL)) before your first call to rand.

Upvotes: 9

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

To loop over the items of a collection the most natural C++ loop is the range based for loop.

In order to assign something to each item, the formal item name should be a reference, thus:

for( auto& item : X )
{
    // E.g. assign to item here.
}

This serves up each item of the array, in order, to the code marked by a comment.

There are two different random generators in C++, the old C library one, which is just a pair of functions, and the more general and modern but also not-so-easy-to-grok C++11 thingy. I suggest you google it and try out things. Ask new more specific question if/when stuck.

Upvotes: 0

Related Questions