john shreef
john shreef

Reputation: 33

How to reset a function variable every n times?

I'm using a random number generating function and it's working fine but I need to reset a function variable nSeed every n times, let's say nSeed=5323 .. how can i return it to it's starting value 5323 every 5 operations i'm not sure how to do it .. here's an example:

unsigned int PRNG()  

{  
    static unsigned int nSeed = 5323;  
    nSeed = (8253729 * nSeed + 2396403);  
    return nSeed  % 32767;
}  

int main()
{
   int count=0;  
   while(count<10)  
   {  
       count=count+1;  
       cout<<PRNG()<<endl;  

          if(count==5)
          {  
               nSeed= 5323;   //here's the problem, "Error nSeed wasn't declared in the scoop"
          } 
   }  
}  

Note : I need to declare the counter in the scoop, not in the function.

Upvotes: 1

Views: 100

Answers (3)

Bathsheba
Bathsheba

Reputation: 234795

If you're only using 5 draws from this generator in a cycle then refactor the whole thing to

int PRNG[5] = {5323, /*ToDo - you work out the other 4 elements*/};

and at the call site use

cout << PRNG[count % 5] << endl;  

else your code will end up looking like something worthy of submission to an obfuscation contest.

You'll need to take steps to avoid a bump when count wraps round to zero. assuming you'll ever reach that point. Perhaps set count to zero when it reaches 5? Or, for I can't resist, start with count = 4, and use

cout << PRNG[++count %= 5] << endl;

nothing that this piece of devilry ++count %= 5 doesn't compile in C!

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

Just use another static variable. For example

unsigned int PRNG()  
{
    const unsigned int INITIAL_SEED = 5323;
    static unsigned int i;
    static unsigned int nSeed;

    if ( i++ % 5 == 0 ) 
    {
        nSeed = INITIAL_SEED;
        i = 1;
    }

    nSeed = (8253729 * nSeed + 2396403);

    return nSeed  % 32767;
} 

Another way is to declare the function with a parameter. For example

unsigned int PRNG( bool reset )  
{
    const unsigned int INITIAL_SEED = 5323;
    static unsigned int nSeed = INITIAL_SEED;

    if ( reset ) nSeed = INITIAL_SEED;

    nSeed = (8253729 * nSeed + 2396403);

    return nSeed  % 32767;
} 

Upvotes: 5

Phydeaux
Phydeaux

Reputation: 2855

Instead of count == 5, use the modulo operator:

if (count % 5 == 0)
{
    nSeed= 5323;
}

This will reset the value every time count is divisible by 5, which will happen once every five iterations since you are incrementing by 1.


As pointed out in comments, you also need to make sure that the variable is in scope.

Upvotes: 2

Related Questions