3

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

Community
  • 1
  • 1
codelop
  • 64
  • 1
  • 2
  • 7
  • 1
    C++ has `std::generate` and it has uniform distributions. – chris Sep 26 '14 at 02:24
  • @chris: I think the OP is at a more basic level. like asking for, where's the darn random function in C++, how to do a loop, so on. – Cheers and hth. - Alf Sep 26 '14 at 02:29
  • @Cheersandhth.-Alf Yes I am still new, can anybody please explain me the basic of it. – codelop Sep 26 '14 at 02:33
  • @user2864740 I have tried to use looping inside looping on it and set the array value to it's looping variabel, can it be achieved like this? I'm going to add my code snippet to the question to make it clear – codelop Sep 26 '14 at 02:34
  • Yes, please do :) Also include a clear description of why it doesn't work, including any relevant compiler errors verbatim. – user2864740 Sep 26 '14 at 02:35
  • done it @user2864740, hope my explanation clear and you could help :) – codelop Sep 26 '14 at 02:39
  • I don't see any "random" going on.. – user2864740 Sep 26 '14 at 02:43
  • @user2864740 could you please give me snippet of the code, maybe in the answer. I am really new to this problem in C++ – codelop Sep 26 '14 at 02:43
  • Or better still, [`std::shuffle`](http://en.cppreference.com/w/cpp/algorithm/random_shuffle) in combination with a generator from [``](http://en.cppreference.com/w/cpp/numeric/random) – WhozCraig Sep 26 '14 at 02:44
  • @user2864740 yes that is, I haven't used random on it, if you could please explain, I'll try to use it, code above is still without random – codelop Sep 26 '14 at 02:45
  • "Hope my explanation clear." - its anything-but-clear. Do you want a sequence of 100 elements where each sequence of ten (0..9, 10..19, etc.) is a random shuffle of unique values in (0..9) ? – WhozCraig Sep 26 '14 at 02:46

5 Answers5

9
#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.

Darren Stone
  • 2,008
  • 13
  • 16
  • Thank you Darren Stone, I am going to try it. What if I want to sort it based on the random number ascendingly? – codelop Sep 26 '14 at 02:54
  • With all due respect, sorting an array of integers in C++ has been explained sufficiently on the internet and StackOverflow already. It is easily found. I hope the random array code above answers your question. – Darren Stone Sep 26 '14 at 02:55
  • Thank you @Darren Stone, actually it helps but I can only pick one answer, which is user2864740's answer for the learning experience and pseudocode given. Thank you – codelop Sep 26 '14 at 04:40
8

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 << " "; 
}
w.b
  • 11,026
  • 5
  • 30
  • 49
  • Thank you for your suggestion, but since I use minGW, the 'random_device' seems cannot be used here, thank you – codelop Sep 26 '14 at 06:49
  • It's part of the standard library so it should be usable (you have to `include `, or try `std::random_device`) – w.b Sep 26 '14 at 06:53
  • Yes I've tried that in another project but minGW compiler seems doesn't support it yet. Here is the error message: `error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options` – codelop Sep 26 '14 at 07:52
5

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.

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Thank you very much, it works and thanks for the learning experience through the pseudocode. I pick this answer to help because of it, thank you @user2864740 :) – codelop Sep 26 '14 at 04:38
0

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • I seem can't figure out what's that auto& item : X means, could you please explain it and how to implement it in my code, referring to my code snippet above, thanks :) – codelop Sep 26 '14 at 02:48
  • `X` is your array. `item` is an arbitrary name chosen to stand for an item of that array (you get a different one each time around the loop, in order). `auto&` is the type of `item`; you could alternatively write `int&` since you know that the basic type is `int`. The `&` says that this is a reference. When it's a reference you can change the item in the array, as opposed to when it's a copy, in which case changing it doesn't change the original array item. – Cheers and hth. - Alf Sep 26 '14 at 02:58
  • oh, and the colon `:` is just part of the range based `for` loop syntax. – Cheers and hth. - Alf Sep 26 '14 at 02:59
0

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/

Arturo
  • 1
  • 3