PDA

View Full Version : How to generate an array of random numbers



baluk
22nd November 2010, 14:59
Hi,


I want to generate an array of random alphabets from A to H. As of my knowldge I can use rand() function to generate but seems bit complex and require more lines of code. I would like to know If there is any Qt function like in Java that can quickly generate numbers.

Thank You,

Baluk

wysota
22nd November 2010, 15:13
What's more quickly than calling rand()?

Zlatomir
22nd November 2010, 15:14
You can use qrand (http://doc.qt.nokia.com/4.6/qtglobal.html#qrand)

baluk
22nd November 2010, 17:40
Hi,

I have tried using the qrand() but I can't able to get the desired output. I want to generate a random set with non-repeatable alphabets. I have tried like this


int array[] = {65,66,67,68,69,70,71,72};
qsrand(time(0));
for(i=0;i < SequenceCount; i++)
{
int j = (qrand() % SequenceCount );
qDebug() << array[j];
}



But in the output I see some repeatable numbers.

wysota
22nd November 2010, 17:51
You mean you want to have a random permutation of the array?


#include <algorithm>

int array[] = {65,66,67,68,69,70,71,72};
std::shuffle(array, array+8);

baluk
22nd November 2010, 18:18
Yes I need the same functionality U have given me. But the statement
std::shuffle(array, array+8); is not recognized. it says "shuffle" is not a member of the std.

then I used
std::rand_shuffle(array, array); but it is giving me some extra garbage values along with the result. like
EBGCAFHD Ã…
@|% .

Zlatomir
22nd November 2010, 18:27
The function name is random_shuffle and you need to include <algorithm>

wysota
22nd November 2010, 18:35
If you print something to the console, it has to end with \0. This is basic C/C++ knowledge.