Solved

Help with random seed

Posted on 2001-09-12
20
468 Views
Last Modified: 2011-10-03
I have a template class called RandomAtom which generates either a random lowercase letter or a random digit.  In my main program I have defined a function called RandomItem.  It is overloaded to produce either a random string of some parameterized length, or a random number of some paramaterized length.  It uses my RandomAtom function.  The problem is this:  I don't know where to set the seed of the RandomAtom class so I can generate lets say 10 distinct strings or numbers.  Someone told me to set the random seed in main, then make the RandomAtom object a parameter of my RandomItem function.  I tried this and it generated the same string/number.  Here is my code:

int randomItem(int len, RandomAtom<int> atom)
{
     int thisDigit = 0;
     int retVal = 0;
     while (thisDigit == 0) thisDigit = atom.randomIntChar();  // first digit cannot be zero
     while (len--)
     {
          retVal *= 10;
          retVal += thisDigit;
          thisDigit = atom.randomIntChar();
     }
     return retVal;
}


char* randomItem(int len, RandomAtom<char> atom)
{
     char *retVal = new char[len + 1]; // new string
     retVal[len] = '\0';
     while (len--) {
          retVal[len] = atom.randomIntChar(); // fill it backwards
     }
     return retVal;
}


int main()
{
     
     RandomAtom<int> atom(GetTickCount());

     for(int i = 0; i < 10; i++)
     {
          cout << randomItem(3, atom) << endl;
     }
     return 0;
}

This code generates the same 3 digit number 10 times.  
Example usage of the class RandomAtom:
RandomAtom<int> atom(seed);  
atom.randomIntChar(); // generate a random digit

Can someone help me find my error?  Thanks.
0
Comment
Question by:nidan
  • 11
  • 6
  • 3
20 Comments
 
LVL 16

Expert Comment

by:imladris
ID: 6477751
I think it would help if you showed the implementation of the RandomAtom object.
0
 
LVL 1

Author Comment

by:nidan
ID: 6477783
// File: RandomAtom.h

#ifndef _RandomAtom_H_
#define _RandomAtom_H_

#include "randInt.h" // defines M
#include <windows.h>

static const char* charAlphabet = "abcdefghijklmnopqrstuvwxyz";
static const int charModBase = 26;
static const int intModBase = 10;

template <class T>
class RandomAtom
{
     public:
          explicit RandomAtom(int seed = 1);
     /*  ...................................................
          Purpose      :  Constructor.  Sets the seed
          Restrictions :  Should only be used with char
                              and int
          Input        :  An integer for the seed
          Description  :  RandomAtom is the constructor for
                              a template class which is specialized
                              for int and char.  It generates a
                              random digit or lowercase letter.
          Example Usage:  RandomAtom<int>  atom();
                              RandomAtom<char> atom();
          ................................................... */
         
          T randomIntChar();
     /*  ...................................................
          Purpose      :  To generate a random digit or
                              lowercase letter
          Restrictions :  Should only be used
                              with the int and char data types
          Output       :  A random digit or int
          Description  :  A member function which generates
                              either a random digit or random
                              lowercase letter
          Example Usage:  int  i = atom.randomIntChar();
                              char c = atom.randomIntChar();
     ................................................... */

     private:
          int state;  // holds the seed
};

// Note:  I had to place the implementation in this file
//        because the compiler didn't allow a separate
//            implementation file.

template <class T>
RandomAtom<T>::RandomAtom(int seed)
{
     if(seed < 0)
          seed += M;
     
     state = seed;
     
     if(state == 0)
          state = 1;
}

template <class T>
T RandomAtom<T>::randomIntChar()
{
     state = nextRand(state);
     return (T)state;
}

// The specialized versions:
// char
template <>
class RandomAtom<char>
{
     public:
          explicit RandomAtom(int seed = 1);
          T randomIntChar();
     private:
          int state;
};

template <>
RandomAtom<char>::RandomAtom(int seed)
{
     if(seed < 0)
          seed += M;
     
     state = seed;
     
     if(state == 0)
          state = 1;
}

template <>
char RandomAtom<char>::randomIntChar()
{
     state = nextRand(state);
     return charAlphabet[state % charModBase];  // return a lowercase letter from charAlphabet
}

// int
template <>
class RandomAtom<int>
{
     public:
          explicit RandomAtom(int seed = 1);
          T randomIntChar();
     private:
          int state;
};

template <>
RandomAtom<int>::RandomAtom(int seed)
{
     if(seed < 0)
          seed += M;
     
     state = seed;
     
     if(state == 0)
          state = 1;
}

template <>
int RandomAtom<int>::randomIntChar()
{
     state = nextRand(state);
     return state % intModBase;  // return a digit
}

#endif
----------------------------------------------------------
// File:  randInt.h

#ifndef _randInt_H_
#define _randInt_H_

const int A = 48271;
const int M = 2147483647;
const int Q = M / A;
const int R = M % A;

int nextRand(int lastState);

#endif

------------------------------------------------------
// File: randInt.cpp

#include "randInt.h"

int nextRand(int lastState)
{
     int tmpState = A * (lastState % Q) - R * (lastState / Q);
     
     if(tmpState >= 0)
          return tmpState;
     else
          return tmpState + M;
}
0
 
LVL 16

Expert Comment

by:imladris
ID: 6477857
Ah, no. Perhaps it had nothing to do with RandomAtom after all (I couldn't see any problem with it anyway).

I think the problem is with GetTickCount. GetTickCount returns a DWORD. If that is larger than an int, in your environment, you will wind up getting the bottom bytes as the seed, and, on a little-endian PC, those are the most significant bytes, and so won't change much.
0
 
LVL 1

Author Comment

by:nidan
ID: 6477883
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 1

Author Comment

by:nidan
ID: 6477893
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 1

Author Comment

by:nidan
ID: 6477903
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 1

Author Comment

by:nidan
ID: 6477912
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 1

Author Comment

by:nidan
ID: 6477928
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 1

Author Comment

by:nidan
ID: 6477948
OK, instead of using GetTickCount I used the time() function for the system time.

RandomAtom<int> atom(int(time(0)));

It still is not working.


0
 
LVL 16

Expert Comment

by:imladris
ID: 6478018
I am not certain about any of this (which is why it is a comment and not an answer). However, time also returns a long, and casting it to an int is going to have the same result (whatever that is).

Perhaps you could inspect what seed RandomAtom is getting with a debugger or a print statement to see if we're on the right track or not.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:nidan
ID: 6478047
Well I did output the results of int(time(0)) to the screen several times. It printed large numbers which would change, beginning with the last digit, everytime I ran it, such as: 1000334876.  So I'm assuming this is the system time in seconds and that this isn't the problem.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6478064
The seed should be in the main.
Example:
#include <time.h>

int main()
{
    srand( (unsigned)time( NULL ) );

    RandomAtom<int> atom(GetTickCount());

    for(int i = 0; i < 10; i++)
    {
         cout << randomItem(3, atom) << endl;
    }
    return 0;
}
0
 
LVL 30

Expert Comment

by:Axter
ID: 6478067
In the above example, srand() takes the seed.
That's the only place you should have this seed, and there should only be one seed.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6478079
You're not using the rand() function any where in your code.
rand() is the function you need to add to your code in order to produce random numbers or char.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6478092
Example code:

using namespace std;

#include <time.h>

template <class T>
class foo
{
public:
     T GetRandObject(void)
     {
          return rand();
     }
};

int main()
{
    srand( (unsigned)time( NULL ) );

    foo<int> foo_int;

    for(int i = 0; i < 10; i++)
    {
         cout << foo_int.GetRandObject() << endl;
    }

    foo<char> foo_char;

     for(int a = 0; a < 10; a++)
    {
         cout << foo_char.GetRandObject() << endl;
    }

    return 0;
}
0
 
LVL 1

Author Comment

by:nidan
ID: 6478116
I tried the first example you gave, but still the same problem.  I looked at your sample code though, and in your class you use rand() whereas in my class I have my own randomizing code which is taken from my textbook.  Maybe that's why srand() isn't working?
0
 
LVL 30

Expert Comment

by:Axter
ID: 6478123
>>in my class I have my own randomizing code which is
>>taken from my textbook.
I couldn't find any random-ness inside that code.  I could not identify anything that looked like a random function.

What book did you take this out of?
0
 
LVL 30

Accepted Solution

by:
Axter earned 100 total points
ID: 6478143
I see the problem with your code.
Try the following modifications.
Change randomItem function so that it takes a reference by adding "&" next atom.

int randomItem(int len, RandomAtom<int> &atom) //There is an "&" next to atom here
{
    int thisDigit = 0;
    int retVal = 0;
    while (thisDigit == 0) thisDigit = atom.randomIntChar();  // first digit cannot be zero
    while (len--)
    {
         retVal *= 10;
         retVal += thisDigit;
         thisDigit = atom.randomIntChar();
    }
    return retVal;
}


You can leave your main function as it was in your original post.
0
 
LVL 1

Author Comment

by:nidan
ID: 6478147
The files randInt.h and randInt.cpp contain the random number code.  The code for these files is listed at the bottom of my very first posting.  This is taken from section 10.4.1 of <u><b>Data Structures & Algorithm Analysis in C++</b></u>, second edition, by Mark Allen Weiss.
0
 
LVL 1

Author Comment

by:nidan
ID: 6478149
I mean the bottom of my second posting.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now